如何将新属性添加到数组的每个对象中

时间:2020-07-26 17:19:27

标签: javascript ecmascript-6 vuejs2 javascript-objects ecmascript-5

如何在对象数组中添加新的2个属性?应该为数组内的每个对象添加这2个属性。这是函数:

selectTag(selectedProduct, selectedTag) {
      this.selectedProducts.filter(item => {
        item.id === selectedProduct.id
      })
      .map(item => {
        item.tagId=selectedTag.id, item.tagTitle = selectedTag.title
        })
    },

下拉

  <b-dropdown aria-role="list">
                <b-button
                  icon-right="caret-down"
                  class="ToolbarButton"
                  size="is-small"
                >
                  <span> {{ selectedProduct.tagTitle }} </span>
                </b-button>

                <b-dropdownitem
                  v-for="selectedTag in selectedProduct.tags"
                  :key="selectedTag.id"
                  aria-role="listitem"
                  @click="selectTag(selectedProduct, selectedTag)"
                >
                  {{ selectedTag.title }}
                </b-dropdownItem>

我尝试了上述功能,但是没有用。地图方法应固定。我正在尝试添加tagId和tagTitle属性,这些属性将从每个产品行的下拉选择中获得价值...如何解决?

7 个答案:

答案 0 :(得分:1)

map函数确实是错误的,您什么也不返回,应该是这样的:

.map(item => ({
     ...item,
     tagId: selectedTag.id,
     tagTitle: selectedTag.title
}))

.map(item => {
  return {
    ...item,
    tagId: selectedTag.id,
    tagTitle: selectedTag.title
  }
})

答案 1 :(得分:1)

使用.map和对象传播语法。

.map(item => ({
    ...item, 
    item.tagId: selectedTag.id, item.tagTitle: selectedTag.title
}))

答案 2 :(得分:1)

您可以在对象上循环并添加属性:

for(let obj of array) {
    obj[key1] = value1;
    obj[key2] = value2;
}

答案 3 :(得分:1)

如果这在Vue.js中,则不能按常规向对象添加属性,因为它不会是反应性的。您需要使用Vue.set:

    selectTag: function(selectedProduct, selectedTag) {
      for (var i = 0; i < this.selectedProducts.length; i++) {
        if (this.selectedProducts[i].id === selectedProduct.id) {
          this.$set(this.selectedProducts[i], "tagId", selectedTag.id);
          this.$set(this.selectedProducts[i], "tagTitle", selectedTag.title);
        }
      }
    }

答案 4 :(得分:0)

尝试一下

var arr =[
{id: 1, turnName: "10_00_am"},
{id: 2, turnName: "10_00_am"},
{id: 3, turnName: "11_00_am"}
];


const addProps = (x) => {
    x.prop1 = 'Alaska';
    x.prop2 = 'Canada';
    return x;
}

var newArr = arr.map(x => addProps(x));
console.log(newArr);

答案 5 :(得分:0)

您可以使用ES6对象传播语法从map函数返回新的更新项。 此外,可以在函数参数本身中对对象属性进行解构,以使其看起来简洁明了。

selectTag(({id}), ({id: tagId, title: tagTitle})) {
    this.selectedProducts.filter(item => item.id === id)
    .map(item => ({...item, tagId, tagTitle}))
}

答案 6 :(得分:0)

在显示的函数中,指出过滤器需要将其结果存储在某个变量中,因为过滤器不会使执行它的数组发生变化。映射不起作用,因为您必须复制对象然后扩展新属性

如果我正确理解了您的问题,请尝试以下示例

const object = {
  selectTag(selectedProduct, selectedTag) {
    const data = this.selectedProducts.filter((item) => {
      item.id === selectedProduct.id;
    });

    return data.map((entry) => ({
      ...entry,
      tagId: selectedTag.id,
      tagTitle: selectedTag.title,
    }));
  },
};