在数组中搜索数据[Node.JS]

时间:2018-09-11 14:21:13

标签: arrays json node.js search find

我有一个问题: (对不起,格式不正确)

我有一个数组:

[
    {
        "data": [
            [
                "kek",
                "lol"
            ],
            [
                "notkek",
                "notlol"
            ]
        ]
    }
]

如果有人写“ kek”,则应在“数据”数组中搜索它,并返回其数组内的“ kek”位置  (["kek","lol"]

及其数组位置

{
    "data": [
        [
            "kek",
            "lol"
         ]}

(在这种情况下为“ data [0]”)

如果有人知道答案,请帮助我

2 个答案:

答案 0 :(得分:1)

方法Array.findIndexArray.includes可能会对您有所帮助

const obj = {
  data: [
    [
      'kek',
      'lol'
    ],
    [
      'notkek',
      'notlol'
    ],
  ],
};

const keyToSearch = 'kek';

// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));

if (index === -1) {
  console.log(`We didn't found ${keyToSearch}`);
} else {
  console.log(`We found ${keyToSearch} at index ${index}`);
}


双索引恢复

const obj = {
  data: [
    [
      'kek',
      'lol'
    ],
    [
      'notkek',
      'notlol'
    ],
    [
      'notkek',
      'notlol',
      'otherstuff',
      'kek',
      'test',
    ],
  ],
};

const keyToSearch = 'kek';

const ret = obj.data.reduce((tmp, x, xi) => {
  // We look for the key
  const index = x.findIndex(y => y === keyToSearch);

  if (index === -1) return tmp;

  return [
    ...tmp,

    {
      absoluteIndex: xi,
      relativeIndex: index,
    },
  ];
}, []);


if (!ret.length) {
  console.log(`We didn't found ${keyToSearch}`);
} else {
  ret.forEach(({
    absoluteIndex,
    relativeIndex,
  }) => console.log(
    `We found ${keyToSearch} at`,
    `data index ${absoluteIndex}, in ${relativeIndex} position`,
  ));
}

答案 1 :(得分:0)

userInput = 'kek'
  let item = data.map((item, indx) => {
     item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
   })

映射数据数组,如果嵌套数组中有您要搜索的项目,则返回该数组的索引以及该数组中该项目的索引