首页 > 解决方案 > 基于Javascript中数组列表中的值返回父键

问题描述

{
"arr1":[
    {
      "name":"something1",
      "id":"233111f4-9126-490d-a78b-1724009fa484"
    },
    {
       "name":"something2",
       "id":"50584c03-ac71-4225-9c6a-d12bcc542951"
    },
    {
       "name":"Unique",
       "id":"43cf14ee58ea4d8da43e9a2f208d215c"
    },
    {
       "name":"something4",
       "id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
    },
    {
       "name":"something5",
       "id":"ef825dc3-003c-4740-955a-bb437cfb4199"
    }
],

"arr2":
 [
   {
     "name":"Unique",
     "id":"43cf14ee58ea4d8da43e9a2f208d215c"}
 ]
}

这是以键和值作为数组的数组列表,我想根据特定值返回所有键;

例如:我想返回父键[arr1,arr2],原因是两个数组都包含一个值Unique,所以我想返回两个值的父键,分别是 arr1 和 arr2 。

注意:该列表可以有 n 个数组。

任何帮助,将不胜感激。提前致谢。

标签: javascriptarraysobject

解决方案


最简单的方法是:

  • 循环遍历对象中的键
  • 检查数组是否包含名称为“唯一”的任何对象
  • 如果是这样,请将 objects 键添加到数组中

const obj = {
  "arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
  "arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
  "arr3": [{ "name": "No unique here","id": "Example" }]
}

// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
  // Use .some to see if any of the objects in this array have the selected name
  const containsUnique = obj[prop].some(o => o.name === 'Unique')
  if (containsUnique) {
    // Add the current key to the array
    keys.push(prop)
  }
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)


推荐阅读