Java Script按值筛选嵌套对象属性



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

在提供的代码示例中,我将需要基于标记来过滤对象。我想得到包括";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"],
}
}

提前感谢!

由于您希望保留对象结构,因此应该使用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"]));

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

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

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.entries(input)
.filter(([, v]) => key.every((ks) => v.tags.includes(ks)))
.reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {});
}
console.log(search(input1, ["a", "b"]));

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);
}

}

最新更新