Issue
I have an array of objects on an array called 'houseList = []' - the data is shown below:
0: {houseCode: '1234', street: 'Grove Street'}
1: {houseCode: '5678', street: 'Pike Street'}
2: {houseCode: '9010', street: 'Park Street'}
I am trying to iterate over that data and add to an object a specific index - I want to add the following property to object #1, so that the data on the array of objects would look like this:
0: {houseCode: '1234', street: 'Grove Street'}
1: {houseCode: '5678', street: 'Pike Street', parking: 'True'}
2: {houseCode: '9010', street: 'Park Street'}
So far, I've tried to push on to the array of objects, but no success. My function for doing so is below. I get an error of "ERROR TypeError: this.houseList[i].push is not a function.
for(let i = 0; i < this.houseList.length; i++) {
if (i === 1) {
this.houseList[i].push({parking: this.ParkingIsTrue})
}
}
I have also tried splicing, but that just creates a new object on the array. Here is my code for the splicing function:
for(let i = 0; i < this.houseList.length; i++) {
if (i === 1) {
this.houseList.splice(i, 0, this.ParkingIsTrue))
}
}
The result of the splicing is:
0: {houseCode: '1234', street: 'Grove Street'}
1: {houseCode: '5678', street: 'Pike Street'}
2: {'True'}
3: {houseCode: '9010', street: 'Park Street'}
My question is, how do I actually go about coding the desired data addition?
Solution
You can work with append parking
property to object as below:
this.houseList.splice(i, 0, {
...this.houseList[i],
parking: this.ParkingIsTrue,
});
References
JavaScript Ellipsis: Three dots ( … ) in JavaScript
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.