简体   繁体   中英

Update only a single key in a javascript object with map

I want to update my thumbnail key in my object.

products :[
 {
    id: 1,
    name: "sth,
    thumb : 'abc.jpg'
 }
];

I want to update the products.thumb of all the objects in that array like thumb: 'server/abc.jpg

searchedProducts = products.map(product => {
    return Object.assign({},
    product, 
    product.thumb = product.thumb ? 'server'+product.thumb : '')
});

Current output

[{
    0: 's,
    1: 'e',
    3: 'r',
    4: 'v',
    5: 'e',
    id: 1,
    thumb :'server/abc.jpg'
}]

You probably meant to use Object.assign like so:

 const products = [ { id: 1, name: 'sth', thumb : 'abc.jpg' } ] const searchedProducts = products.map(product => { return Object.assign({}, product, { thumb: product.thumb ? 'server/' + product.thumb : '' }) }) console.log(searchedProducts) 

In the above snippet I'm merging:

  • An empty object.
  • With the currently iterated product object.
  • With another object containing the computed thumb key.

Why would this not work for you?

 const products = [ { id: 1, name: 'sth', thumb : 'abc.jpg' }, { id: 2, name: 'sth', thumb : 'def.jpg' } ]; // Non mutating let copy = JSON.parse(JSON.stringify(products)); copy.forEach(product => { product.thumb = product.thumb ? 'copyserver/'+product.thumb : ''; }); console.log(copy); // Mutating products.forEach(product => { product.thumb = product.thumb ? 'server/'+product.thumb : ''; }); console.log(products); 

With spread syntax:

 const products = [ { id: 1, name: 'sth', thumb : 'abc.jpg' } ]; searchedProducts = products.map(product => { const thumb = product.thumb ? 'server/' + product.thumb : ''; return { ...product, thumb }; }); console.log(searchedProducts); 

You can use destructing assignment with .map to modify all thumb properties.

See working example below:

 const products = [{id:1,name:"sth",thumb:"abc.jpg"},{id:2,name:"byt",thumb:"def.jpg"},{id:3,name:"mth"}], res = products.map(({thumb, ...others}) => ({...others, "thumb": thumb ? "server/" + thumb:''})); console.log(res); 

You could destructure and get the thumb property and keep the remaining properties in rest . This way you can keep the remaining properties as they are:

 const products = [{ id: 1, name: "sth", thumb: 'abc.jpg' }, { id: 2, name: "sth2", thumb: 'def.jpg' } ]; const newProducts = products .map(({thumb, ...rest}) => ({ thumb: thumb ? `server/${thumb}` : ``, ...rest })); console.log(newProducts) 

You could also do this using reduce , initialising your start with an empty array,

const result = products.reduce((prev, next) => {
  next.thumb = `server/${next.thumb}`;
  prev.push(next);
  return prev;
}, []);

console.log(result);

Just another way of doing it other than map .

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