在数组中推送对象创建另一个数组

时间:2019-01-21 15:13:56

标签: javascript

我有这个数组:

var arr = this.products.find(x => x.id == 3);

我正在尝试在此数组中推送一个对象,例如:

arr.push({ id: "5", name: "foo3" });

问题是我得到一个包含两个数组的数组。

注意:this.products是在类的原型中定义的,并且包含对象数组

console.log(arr):

[Array(4)]
0: Array(4)
0: {id: "1", name: "test"}
1: {id: "2", name: "foo"}
2: {id: "3", name: "foo2"}
length: 3
__proto__: Array(0)
length: 1
__proto__: Array(0)

2 个答案:

答案 0 :(得分:0)

let arr = [
   { id: "1", option: { bound_id: "2" }},
   { id: "2", option: { bound_id: "12" }},
   { id: "12", option: { bound_id: "2" }}
]
    
arr.push({ id: "5", option: { bound_id: "4" }})
    
console.log(arr)

请确保这正是您的代码编写方式。如果是这样的话。

答案 1 :(得分:0)

首先,find将返回找到的第一个元素,该元素满足您通过documentation says.

传递的功能

第二秒,对象没有push功能。

如下面的代码片段所示,您的代码无法正常工作,但是我们可能会对您的尝试有所了解。

this.products = [{
    id: "1",
    option: {
      bound_id: "5"
    }
  },
  {
    id: "2",
    option: {
      bound_id: "8"
    }
  },
  {
    id: "3",
    option: {
      bound_id: "1"
    }
  },
  {
    id: "4",
    option: {
      bound_id: "1"
    }
  }
]
var arr = this.products.find(x => x.id == 3);

console.log("this IS NOT AN ARRAY", arr)

//this isnt a function, it doesnt even work.
arr.push({
  id: "5",
  name: "foo3"
});

现在让我们尝试看看您要做什么:

1)完成一个新数组,该数组同时包含上一个数组和最后一个新选项。

2)数组过滤器将ID === 3的那些过滤器

let arr = [{
    id: "1",
    option: {
      bound_id: "5"
    }
  },
  {
    id: "2",
    option: {
      bound_id: "8"
    }
  },
  {
    id: "3",
    option: {
      bound_id: "1"
    }
  },
  {
    id: "4",
    option: {
      bound_id: "1"
    }
  }
]

const otherObj = {
  id: "5",
  option: {
    bound_id: "4"
  }
}

//complete new array containing both, previous array and the new option at the end.
const newArray = [...arr, otherObj]

//array filterinr the ones with ID === 3
const newArrayFiltered = [...arr.filter(i => i.id !== "3"), otherObj]

console.log(newArray)
console.log(newArrayFiltered)