合并共享相同属性值的两个JavaScript数组对象

时间:2019-02-21 06:25:07

标签: javascript arrays object

我有两个JavaScript对象,如下所示。

obj1 = {
  sdfjjweifh: {
    user: "bob@bob.com",
    id: "10"
  },
  fjemsnduci: {
    user: "fred@fred.com",
    id: "20"
  },
  dhcnwodpcu: {
    user: "joe@joe.com",
    id: "30"
  }
};

obj2 = [{
  Name: "Bob",
  Id: "10"
}, {
  Name: "Fred",
  Id: "20"
}, {
  Name: "Joe",
  Id: "30"
}];

我想将其与“ id”字段匹配的结果结合起来:

obj1 = {
  sdfjjweifh: {
    user: "bob@bob.com",
    id: "10",
    Name: "Bob"
  },
  fjemsnduci: {
    user: "fred@fred.com",
    id: "20",
    Name: "Fred"
  },
  dhcnwodpcu: {
    user: "joe@joe.com",
    id: "30",
    Name: "Joe"
  }
};

使用纯javascript / ES6最简单的方法是什么?

我发现很多与此相关的东西,但不能完全整合在一起。

2 个答案:

答案 0 :(得分:0)

您可以在if(isset($_SESSION['login_account_id'])){ header('location: /index.php'); } 的键上使用forEach()循环,以便对于obj1的每个属性,可以在数组obj1中找到对应的匹配对象:

obj2

答案 1 :(得分:0)

使用for..in遍历对象并从每个对象获取ID。然后使用数组findIndexId匹配的数组中获取对象的索引。如果Id匹配,则从数组中获取其名称,然后在对象中添加新键

let obj1 = {
  sdfjjweifh: {
    user: "bob@bob.com",
    id: "10"
  },
  fjemsnduci: {
    user: "fred@fred.com",
    id: "20"
  },
  dhcnwodpcu: {
    user: "joe@joe.com",
    id: "30"
  }
};

let obj2 = [{
  Name: "Bob",
  Id: "10"
}, {
  Name: "Fred",
  Id: "20"
}, {
  Name: "Joe",
  Id: "30"
}];


for (let keys in obj1) {
  if (obj1[keys].hasOwnProperty('id')) {
    let keyIndex = obj2.findIndex(function(item) {
      return item.Id === obj1[keys].id
    });
    if (keyIndex !== -1) {
      obj1[keys].Name = obj2[keyIndex].Name
    }
  }
}
console.log(obj1)