合并两个对象数组并添加新的键和值

时间:2019-05-29 11:03:59

标签: javascript arrays

我有两个基于“ Form_Name”键值的数组,用于合并具有新键和值“ isChecked”的数组。

第一个阵列

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="buttons" style="display:inline-block;">
  <button id="first">FIRST</button>
  <button id="second">SECOND</button>
</div>
<button id="both">BOTH</button><br>
<div id="result"></div>

第二个数组

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];

预期的合并数组

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];

我尝试如下

mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]

3 个答案:

答案 0 :(得分:2)

 const hasChecked = new Set(arrayOne.map(it => it.Form_Name));

 const result = arrayTwo.map(it => ({ ...it, isChecked: hasChecked.has(it.Form_Name) }));

通过创建一组选中的表单名称,您可以轻松地在第二个对象数组上进行映射,并添加一个isChecked属性。

答案 1 :(得分:0)

let arrayOne = [{
  id: 11,
  Form_Name: "form name One",
  isChecked: true
}, {
  id: 11,
  Form_Name: "form name Two",
  isChecked: true
}];

let arrayTwo = [{
  Form_Name: "form name One",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Two",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Three",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Four",
  Form_AddDate: "2019-05-15T11:03:18.05"
}];

let arrayOneObj = arrayOne.reduce((result, item) => {
  result[item.Form_Name] = item.isChecked
  return result;
}, {})

const result = arrayTwo.map((item) => ({ ...item,
  isChecked: !!arrayOneObj[item.Form_Name]
}))

console.log(result);

答案 2 :(得分:0)

如果两个数组中的form_name顺序相同,请尝试此操作。

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true},
{id: 11, Form_Name: "form name Two", isChecked: true},
{id: 11, Form_Name: "form name Three", isChecked: true},
{id: 11, Form_Name: "form name Four", isChecked: true}]

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}]

let mergedArray = []

arrayTwo.forEach( (item,i) => { mergedArray.push(Object.assign({}, item, arrayOne[i]))} )

console.log(mergedArray)

希望有帮助!