替换VueJs数组中的值

时间:2020-03-14 22:20:51

标签: javascript arrays vue.js

我有两个数组:

1)listArray,其格式如下:

0: {value: "373", text: "1 - First Item in the Array"}
1: {value: "343", text: "2 - Second Item in the Array"}
2: {value: "376", text: "3 - Third Item in the Array"}

2)displayArray,其格式如下:

0: {name: "Number One", position: "373", additionalinfo: "Description Goes Here"}
1: {name: "Number Two", position: "343", additionalinfo: "Description Goes Here"}
2: {name: "Number three", position: "376", additionalinfo: "Description Goes Here"}

我想让第二个数组displayArray使用来自listArray的信息看起来像这样:

0: {name: "Number One", position: "1 - First Item in the Array", additionalinfo: "Description Goes Here"}
1: {name: "Number Two", position: "2 - Second Item in the Array", additionalinfo: "Description Goes Here"}
2: {name: "Number three", position: "3 - Third Item in the Array", additionalinfo: "Description Goes Here"}

我不介意创建第三个数组,但是当我尝试在array.push中使用它时,出现了错误。我该怎么办?

1 个答案:

答案 0 :(得分:1)

选项1:更改displayArray

使用forEach

displayArray.forEach((item, index) => {
  item.position = listArray[index].text;
})

选项2:创建一个新数组

使用map

const newArray = displayArray.map((item, index) => {
  const newitem = Object.assign({}, item);
  newitem.position = listArray[index].text;
  return newitem;
})

这里是demo