简体   繁体   中英

Can you splice a single object property in an array of objects?

I'm wondering if it's possible to mutate a specific object property in an array of objects using the splice method.

For example

const array = [
    { name: 'Object 1', body: 'Hello world'},
    { name: 'Object 2', body: 'Bye Pluto'}
]

array.splice(1, 1, /* Can I mutate [1].body without replacing the whole object? */)

Expected output would be:

{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Jupiter'}

You could take a property accessor with the array, index and property without splicing the array.

 const array = [{ name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'}]; array[1].body = 'Bye Mars!'; console.log(array); 

 const array = [ { name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'} ] array[1].body = "New Content" console.log(array) 

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. So you can never use splice to update objects in the array without removing it.

What you want to achieve can easily be done with

 const array = [ { name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'} ] array[1].body = 'Bye Jupiter 1' console.log(array) array[1]['body'] = 'Bye Jupiter 2' console.log(array) 

If you use splice to do this.

 const array = [ { name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'} ]; array.splice(1, 1, {...array[1], body: 'Bye Jupiter'}) console.log(array) 

Of course you can do it easy.

 const array = [ { name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'} ] array[1].body = 'Bye Jupiter'; console.log(array) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM