Найти индекс элемента массива из другого элемента массива json - PullRequest
0 голосов
/ 03 июля 2019

Я ищу, чтобы найти индекс и сгруппировать элемент, к которому принадлежит элемент в родительской группе json, как я могу это сделать?Я открыт для переформатирования json, если это необходимо,

Я пробовал JSON.stringify (), но он также возвращает неверный индекс.

let Content = {
    group1: [
      [{content:"hello"},{content:"world"}],
      [{content:"hello1"},{content:"world"}],
      [{content:"hello2"},{content:"world"}],
      [{content:"hello3"},{content:"world"}],
      [{content:"hello4"},{content:"world"}],
      [{content:"hello5"},{content:"world"}],
    ],
    group2: [
      [{content:"hello10"},{content:"world"}],
      [{content:"hello11"},{content:"world"}],
      [{content:"hello12"},{content:"world"}],
      [{content:"hello13"},{content:"world"}],
      [{content:"hello14"},{content:"world"}],
      [{content:"hello15"},{content:"world"}],
    ],
  };
//   let currentItem = {type:'group2',index:5};
//   let currentItemContent = Content[currentItem.type][currentItem.index];
let obj = [{content:"hello15"},{content:"world"}];
let newIndex =  Content["group1"].indexOf(obj); 
let type = "group1"; 
if(newIndex < 0)
{
  type="group2"
  console.log(Content["group2"]);
  newIndex = Content["group2"].indexOf(obj); 
}
console.log({"type":type,"index":newIndex});

expected: {type:'group2',index:5}

Ответы [ 2 ]

1 голос
/ 03 июля 2019

Перебрать объект Content с помощью for...in. Проверьте, входит ли данный массив в каждую группу, используя findIndex. Поскольку оба объекта в массиве кажутся в порядке, вы можете просто сравнить строку, возвращаемую JSON.stringify

let Content={group1:[[{content:"hello"},{content:"world"}],[{content:"hello1"},{content:"world"}],[{content:"hello2"},{content:"world"}],[{content:"hello3"},{content:"world"}],[{content:"hello4"},{content:"world"}],[{content:"hello5"},{content:"world"}]],group2:[[{content:"hello10"},{content:"world"}],[{content:"hello11"},{content:"world"}],[{content:"hello12"},{content:"world"}],[{content:"hello13"},{content:"world"}],[{content:"hello14"},{content:"world"}],[{content:"hello15"},{content:"world"}]]}

function find(input, search) {
  for (const type in input) {
    const group = input[type];
    const index = group.findIndex(a => JSON.stringify(a) === JSON.stringify(search));
    
    if (index != -1)
      return { type, index }
  }
  return null
}

console.log(find(Content, [{content:"hello15"},{content:"world"}]))
console.log(find(Content, [{content:"hello"},{content:"world"}]))
0 голосов
/ 03 июля 2019

Вы также можете использовать Array.find в сочетании с Object.keys и Array.some. Сравнение массивов вы можете сделать через JSON.stringify, однако помните, что если ваши ключи в другом порядке, это не сработает:

[{content:"world"},{content:"hello"}] vs [{content:"hello"},{content:"world"}]

не будет соответствовать, как вы ожидаете, так как вы сопоставляете строки, и теперь они другие.

let Content = { group1: [ [{content:"hello"},{content:"world"}], [{content:"hello1"},{content:"world"}], [{content:"hello2"},{content:"world"}], [{content:"hello3"},{content:"world"}], [{content:"hello4"},{content:"world"}], [{content:"hello5"},{content:"world"}], ], group2: [ [{content:"hello10"},{content:"world"}], [{content:"hello11"},{content:"world"}], [{content:"hello12"},{content:"world"}], [{content:"hello13"},{content:"world"}], [{content:"hello14"},{content:"world"}], [{content:"hello15"},{content:"world"}], ], };
	    	
let findArray = (data, obj) => {
  let index, group = Object.keys(data).find((k,i) => {
    index = i
    return data[k].some(x => JSON.stringify(x) === JSON.stringify(obj))
  })
  return { index, group }
}

console.log(findArray(Content, [{content:"hello"},{content:"world"}]))
console.log(findArray(Content, [{content:"hello10"},{content:"world"}]))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...