Java 脚本按值过滤嵌套对象属性

Java Script filter nested object properties by value

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

在提供的代码示例中,我需要根据标签过滤对象。我想获取在标签数组中包含“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"],
    }
}

提前致谢!

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

因为你想保留对象结构,你应该使用 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"]));

您可以使用 Object.entries to get the [key, value] pair as an array of an array then you can use filter to filter out the elements that don't contain the element in the key array. Finally, you can use 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);
}

}