【问题标题】:Replacing value inside VueJs Array替换 VueJs 数组中的值
【发布时间】:2020-06-26 11:52:21
【问题描述】:

我有两个数组:

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 中使用它时,出现错误。我该怎么做?

【问题讨论】:

  • 您尝试过什么,遇到了什么错误? forEachmap 应该这样做。
  • 如何有条件地从数组 1 获取数据并替换数组 2?
  • 这不是错误,而是通过将数组 2 中的位置值替换为数组 1 中的文本值,它不起作用

标签: javascript arrays vue.js


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2013-09-11
    • 2021-04-06
    • 1970-01-01
    • 2014-03-09
    相关资源
    最近更新 更多