没有得到整个扁平化的javascript对象结构

时间:2018-05-14 15:33:20

标签: javascript node.js recursion

我有一个嵌套对象,我希望从中检索某些键/值对。要检索这些内容,必须为每个键设置一个值。

我已经关闭,但我没有得到任何嵌套对象'键/值对。

我创建了this fiddle

这是我目前的职能:

function getKeysVals(obj, keys, recurse = false)
{
  let addToOutput = true;
  let out         = [];
  let cnt         = 0;
  obj.map
  (
    (thisObj) =>
    {
      let newObj = {};  // Temp holder for new object that gets added to output.

      // Loop through the requested keys, adding them to the new object:
      for( i in keys)
      {
        // Check that this key has a value:
        if(!thisObj[keys[i]])
        {
          addToOutput = false;
          break;
        }
        else
        {
          newObj[keys[i]] = thisObj[keys[i]];
        }
      }

      // Ensure we have values for ALL the requested keys in this object:
      if( addToOutput ) out.push(newObj);

      // Go round again if this object has the specified recurse object:
      if( thisObj[recurse] )
      {
        getKeysVals(thisObj[recurse], keys, recurse)
      }
    }
  );
  return out
}

当我用result = getKeysVals(nodes[0].nodes, ['id', 'text', 'filePath'], 'nodes');调用它时,我希望得到一个新数组:

[
    { id: 1526297185466,​​​​​ text: 'test part a',​​​​​ filePath: 'test part a-1526297185451.CSV' },
    { id: 1526297202132,​​​​​ text: 'test part B',​​​​​ filePath: 'test part B-1526297202118.CSV' },​​​​​
    { id: 1526297209980,​​​​​ text: 'Test Part C',​​​​​ filePath: 'Test Part C-1526297209966.CSV' }
]

但我只得到:

[{ id: 1526297185466,​​​​​ text: 'test part a',​​​​​ filePath: 'test part a-1526297185451.CSV' }]

整个对象:

[{
"id": 1526297177970,
"text": "k",
"nodes": [
  {
    "id": 1526297185466,
    "tags": [1],
    "text": "test part a",
    "state": { "checked": true, "expanded": true },
    "filePath": "test part a-1526297185451.CSV"
  },
  {
    "id": 1526297195199,
    "tags": [1],
    "text": "New Product Set",
    "nodes": [
      {
        "id": 1526297202132,
        "tags": [1],
        "text": "test part B",
        "state": { "checked": true, "expanded": true },
        "filePath": "test part B-1526297202118.CSV"
      },
      {
        "id": 1526297209980,
        "tags": [1],
        "text": "Test Part C",
        "state": { "checked": true, "expanded": true },
        "filePath": "Test Part C-1526297209966.CSV"
      }
    ],
    "state": { "checked": true }
  }
],
"state": { "checked": true }
}]

1 个答案:

答案 0 :(得分:1)

如果你打电话

 getKeysVals(thisObj[recurse], keys, recurse)

这将创建一个新的out并返回该值,因此您可以将其添加到当前输出中:

out.push(...getKeysVals(thisObj[recurse], keys, recurse));