Javascript - 按特定值比较两个数组并创建一个填充匹配的新数组

时间:2017-07-25 19:13:56

标签: javascript arrays

请假设我有两个阵列充满了这样的对象:

var arr1 = [{dog: "bark", cat: "meow", cow: "muh"}, {dog: "barking", cat: "meow", cow: "muhing"}]
var arr2 = [{cat: "meow", dog2: "barked"}, {cow: "muhed", savage: "phew", cat: "meowed"}]

我希望得到这样的结果:

var arr3 = [{dog: "bark", cat: "meow", cow: "muh", dog2: "barked"}]

arr1arr2在某些对象中有一个公共键值对,它是cat: "meow"我希望这些对象合并并推送到另一个数组{{1在我的情况下。它甚至可能吗?提前谢谢!

2 个答案:

答案 0 :(得分:-1)

请试试这个:

var _ = require('lodash');

var a = [{a:1, b:2}];
var b = [{a:1, b:2, c:3}];

_.merge(a, b);

//输出:{a:1, b:2, c:3}

看看这是否适合你。

答案 1 :(得分:-1)

这是另一种解决方案,纯粹的js。

注意:我相信您错过了预期结果中的const arr1 = [{dog: "bark", cat: "meow", cow: "muh"}, {dog: "barking", cat: "meow", cow: "muhing"}]; const arr2 = [{cat: "meow", dog2: "barked"}, {cow: "muhed", savage: "phew", cat: "meowed"}]; const combinedArr = [...arr1, ...arr2]; const obj = {}; combinedArr.forEach((v, i) => { Object.keys(v).forEach(c => !obj[c] ? obj[c] = combinedArr[i][c] : null); }); console.log(obj);键。



@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

@Entity
public class Child implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn
    private Parent parent;  
}
&#13;
&#13;
&#13;