如何提取嵌套对象数组的值?

时间:2017-12-17 04:48:10

标签: javascript arrays ecmascript-6

我正在尝试提取下面显示的对象数组的所有链接ID。这就是我试图做到的方式:

const linkIDs = array
  .filter(d => d.links)
  .map(d => d.links)

但这给了我一个嵌套数组,这不是我想要的。

[
  {
    "id: "1",
    "links": [
        {
            "id" : "Dn59y87PGhkJXpaiZ",
            "type" : "article"
        },
      {
            "id" : "PGhkJXDn59y87paiZ",
            "type" : "article"
        }
    ]
  },
  {
    "id: "2",
    "links": [
        {
            "id" : "GhkJXpaiZDn59y87P",
            "type" : "article"
        }
    ]
  },
  {
    "id": "3"
  }
]

所以在这个例子中我需要结果

[ "Dn59y87PGhkJXpaiZ", "PGhkJXDn59y87paiZ", "GhkJXpaiZDn59y87P" ]

3 个答案:

答案 0 :(得分:1)

你可以在不使用任何其他库的情况下做到如下。



var data = [
  {
    "id": "1",
    "links": [
        {
            "id" : "Dn59y87PGhkJXpaiZ",
            "type" : "article"
        },
       {
            "id" : "PGhkJXDn59y87paiZ",
            "type" : "article"
        }
    ]
  },
  {
    "id": "2",
    "links": [
        {
            "id" : "GhkJXpaiZDn59y87P",
            "type" : "article"
        }
    ]
  },
  {
    "id": "3"
  }
];

var result = data.filter(e => e.links)
                 .map(e => e.links.map(link => link.id))
                 .reduce((a, b) => a.concat(b), []);
                
console.log(result);




答案 1 :(得分:1)

您需要在映射之前生成数组。 Js中的Reduce是非常有用的功能;)



arr = [
  {
    "id": "1",
    "links": [
        {
            "id" : "Dn59y87PGhkJXpaiZ",
            "type" : "article"
        },
      {
            "id" : "PGhkJXDn59y87paiZ",
            "type" : "article"
        }
    ]
  },
  {
    "id": "2",
    "links": [
        {
            "id" : "GhkJXpaiZDn59y87P",
            "type" : "article"
        }
    ]
  },
  {
    "id": "3"
  }
];

var result = arr.filter(a=>a.links).reduce((acc, a) => {
 return acc.concat(a.links)
}, []).map(a=>a.id);
console.log(result);




答案 2 :(得分:0)

您可以使用lodash的flatMap(),其中每个过滤的项目都使用map()进行转换。

<强>样本

&#13;
&#13;
var data = [
  {
    "id": 1,
    "links": [
      {
        "id": "Dn59y87PGhkJXpaiZ",
        "type": "article"
      },
      {
        "id": "PGhkJXDn59y87paiZ",
        "type": "article"
      }
    ]
  },
  {
    "id": "2",
    "links": [
      {
        "id": "GhkJXpaiZDn59y87P",
        "type": "article"
      }
    ]
  },
  {
    "id": "3"
  }
];
var result =  _.flatMap(data, item => 
  _(item.links)
    .map(v => (v.id))
    .value()
);
           
console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>
&#13;
&#13;
&#13;