javascript - 从另一个 json 数组项中查找数组项的索引

标签 javascript arrays json indexing find

我正在寻找父 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}

最佳答案

使用 for...in 循环访问 Content 对象。使用 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"}]))

关于javascript - 从另一个 json 数组项中查找数组项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875944/

相关文章:

c++ - STL推回: previous values getting modified when pushing a dynamically changing array

PHP > json_encode ,强制创建一个数组,即使它只有一个元素

jquery - 将序列化表单的数据转换为 json 对象

ios - JSON 到 NSDictionary 文字

javascript - selenium webdriver javascript 查询

javascript - 为什么CreateJS不绘图?

arrays - 为什么 Swift 有时会将混合类型数组视为单一类型数组?

javascript - 使用 node.js 上传后解析 CSV 的第一行

javascript - 单击按钮时的appendChild()问题

arrays - 在 AngularJs 中使用 $resource 来保存对象数组