JavaScript对象数组包含相同的数组数据 [英] JavaScript array of objects contains the same array data

查看:65
本文介绍了JavaScript对象数组包含相同的数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将所有相同的数据值放入对象数组.这是我的输入:

I try to get all same data values into an array of objects. This is my input:

var a = [{
    name: "Foo",
    id: "123",
    data: ["65d4ze", "65h8914d"]
  },
  {
    name: "Bar",
    id: "321",
    data: ["65d4ze", "894ver81"]
  }
]

我需要这样的结果:

["65d4ze"]

我尝试在对象上循环以获取此输出,但是我完全迷失了……我不知道如何知道结果是否进入所有数据数组.

I try to loop on my object to get this output, but I'm completely lost... I don't know how to know if the result is into all data arrays.

var a = [{
        name: "Foo",
        id: "123",
        data: ["65d4ze", "65h8914d"]
      },
      {
        name: "Bar",
        id: "321",
        data: ["65d4ze", "894ver81"]
      }
    ],
  b = [],
  c = []
a.forEach(function(object) {
  b.push(object.data.map(function(val) {
    return val;
    })
  );
});

console.log(b);

推荐答案

您可以映射 data 并使用 Set Set#has .

You could map data and get the common values with Array#map, Array#reduce, Array#filter, Set and Set#has.

var array = [{ name: "Foo", id: "123", data: ["65d4ze", "65h8914d"] }, { name: "Bar", id: "321", data: ["65d4ze", "894ver81"] }],
    key = 'data',
    common = array
        .map(o => o[key])
        .reduce((a, b) => b.filter(Set.prototype.has, new Set(a)));

console.log(common);

这篇关于JavaScript对象数组包含相同的数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆