从对象和嵌套数组中提取键

时间:2018-05-31 09:42:33

标签: javascript arrays functional-programming

我有一个对象数组,这些对象在某些情况下也有嵌套数组,其中包含对象。

每个对象都是我需要提取的属性key

我正在处理的JSON的一个例子是......

{
"items": [  
   {  
      "key":"main",
      "foo":"bar",
      "children":[  
         {  
            "key":"one",
            "foo":"barboo"
         },
         {  
            "key":"two",
            "foo":"boobaz"
         }
      ]
   },
   {  
      "key":"secondary",
      "foo":"baz",
      "children":[  
         {  
            "key":"one",
            "foo":"barboobaz"
         },
         {  
            "key":"two",
            "foo":"boobazfoo"
         }
      ]
   }
]
}

目前我正在映射items并返回key,然后在我找到孩子的地方再次映射key

像这样的伪代码......

class SomeClass {
let contentKeys = []


    extractKeys = navItems => {
        navItems.map(item => this.appendToContentRequest(item));
        return this.contentKeys.join(',');
    };

    appendToContentRequest(item) {
        if (~!this.contentKeys.indexOf(item.key)) {
            this.contentKeys.push(item.key);
        }
        if (item.children) {
            item.children.map(child => this.appendToContentRequest(child));
        }
    }


}

我不喜欢这个,但感觉非常'hacky'而且不是很实用。

有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以使用下面的递归函数来获取任何嵌套对象数组的任何键值



function extract(array, keyName) {
  return array.reduce((a, b) =>
    a.concat(...Object.keys(b).map(e => e === keyName ? b[e] : (Array.isArray(b[e]) ? extract(b[e], keyName) : null))), []).filter(e => e);
}

console.log(extract(obj.items, 'key'));

<script>
  const obj = {
    "items": [{
        "key": "main",
        "foo": "bar",
        "children": [{
            "key": "one",
            "foo": "barboo"
          },
          {
            "key": "two",
            "foo": "boobaz"
          }
        ]
      },
      {
        "key": "secondary",
        "foo": "baz",
        "children": [{
            "key": "one",
            "foo": "barboobaz"
          },
          {
            "key": "two",
            "foo": "boobazfoo"
          }
        ]
      }
    ]
  }
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var data = {
"items": [  
   {  
      "key":"main",
      "foo":"bar",
      "children":[  
         {  
            "key":"one",
            "foo":"barboo"
         },
         {  
            "key":"two",
            "foo":"boobaz"
         }
      ]
   },
   {  
      "key":"secondary",
      "foo":"baz",
      "children":[  
         {  
            "key":"one",
            "foo":"barboobaz"
         },
         {  
            "key":"two",
            "foo":"boobazfoo"
         }
      ]
   }
]
}


 function flatNestedKey(array) {
    var result = [];
    const context = this;
    array.forEach(function (a) {
      result.push(a.key);
      if (Array.isArray(a.children)) {
        result = result.concat(context.flatNestedKey(a.children));
      }
    });
    return result;
  }
  
  var keys = flatNestedKey(data.items);
  console.log(keys);

相关问题