[英]Push object in array create another array
我有这个数组:
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)
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)
请确保这正是您编写代码的方式。 如果是这样它是正确的。
首先, find
将返回find
的第一个满足您按照文档所述传递的函数的元素。
其次,对象没有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) 数组 filterinr 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.