将对象的属性值添加到对象数组

时间:2019-06-08 17:09:04

标签: javascript arrays loops

我有一个数组对象和一个与数组具有相同数量属性的对象。

我需要将对象的属性值附加到数组的每个对象。 填充值属性

数组

0: {number: "1", type: "date", placeholder: "Semana", validations: Array(1), value: "value"}
1: {number: "2", type: "text", placeholder: "Marca", validations: Array(3), value: "value"}
[n]

对象

0: "23"
1: "34"
2: "sdfds"
[n]

代码

this.dataForm.forEach( (el) => {
    Object.entries(formObject).forEach(([key, value]) => {
      el.value = value
    })
})

您能帮忙吗?

预期结果

0: {number: "1", type: "date", placeholder: "Semana", validations: Array(1), value: 23}
1: {number: "2", type: "text", placeholder: "Marca", validations: Array(3), value: 34}

2 个答案:

答案 0 :(得分:2)

您可以使用map()

const arr = [{number: "1", type: "date", placeholder: "Semana", validations: Array(1), value: "value"},
{number: "2", type: "text", placeholder: "Marca", validations: Array(3), value: "value"}]

const obj = {
  0: "23",
  1: "34",
  2: "sdfds"
}

const res = arr.map((x,i) => ({...x,value:obj[i]}))
console.log(res)

答案 1 :(得分:0)

您可以使用forEach并在每次迭代中访问实际索引以设置适当的值:

data = [
    {number: "1", type: "date", placeholder: "Semana", validations: Array(1), value: "value"},
    {number: "2", type: "text", placeholder: "Marca", validations: Array(3), value: "value"}
  ]
values = ["23", "34"]

// Here you do the magic :)
data.forEach((row, index) => row.value = values[index])