Java Script 按值过滤嵌套对象属性

时间:2021-07-19 10:44:22

标签: javascript arrays filter nested-object

我需要按属性值过滤嵌套对象。我知道以前有人问过类似的问题,但我找不到值存储在数组中的情况的解决方案。

在提供的代码示例中,我需要根据标签过滤对象。我想获取标签数组中包含“a”和“b”的对象。

const input1 = {
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "1":{
        "id":"02",
        "name":"item_02",
        "tags":["a","c","d"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}
 
function search(input, key) {
   return Object.values(input).filter(({ tags }) => tags === key);
}

console.log(search(input1, "a"));

作为输出,我想收到休耕:

{
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}

非常感谢!

4 个答案:

答案 0 :(得分:1)

既然你想保留对象结构,你应该使用 Object.entries 而不是 Object.values 并恢复到对象类型使用 Object.fromEntries:

Object.fromEntries(Object.entries(input).filter(...))

要使其适用于多个键,请将 everyincludes 结合用作谓词:

keys.every(key => tags.includes(key))

const input1 = {
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "1":{
        "id":"02",
        "name":"item_02",
        "tags":["a","c","d"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}
 
function search(input, keys) {
   return Object.fromEntries(
   Object.entries(input).filter(([, { tags }]) => keys.every(key => tags.includes(key)))
   )
   
}

console.log(search(input1, ["a", "b"]));

答案 1 :(得分:0)

function search(input, key) {
  Object.values(input).filter(x=>x.tags.includes(key))
}

答案 2 :(得分:0)

您可以使用Object.entries来获取[key, value]对作为数组的数组,然后您可以使用filter过滤掉不包含{中的元素的元素{1}} 数组。最后,您可以使用 reduce 生成单个值,即作为最终结果的对象

key

答案 3 :(得分:0)

   function search(input, tagsToFind) {
  return Object.values(input).filter(inputItem => {
    tagsToFind = Array.isArray(tagsToFind) ? tagsToFind : [tagsToFind];
    let tagFound = false;
    for (const key in tagsToFind) {
      if (Object.prototype.hasOwnProperty.call(tagsToFind, key)) {
        const element = tagsToFind[key];
        if (inputItem.tags.indexOf(element) === -1) {
          tagFound = false;
          break;
        } else {
          tagFound = true;
        }
      }
    }

    return tagFound;
  })

  // ({ tags }) => tags === key);
}

}