Map over an object and change one properties value using native JS

后端 未结 6 1429
生来不讨喜
生来不讨喜 2021-02-06 22:50

I want to be able to return a result set of data and just change the formatting of the date field to something more readable leaving all the other data intact. I would prefer t

6条回答
  •  别跟我提以往
    2021-02-06 23:24

    You can use Object.assign(target, ...sources) (here) of which you want to change only one value by keeping other values intact.

    For example:

    const object1 = {
     a: 1,
     b: 2,
     c: 3
    };
    

    Now suppose you want to change the value of b to 22, you can do this by:

    const object2 = Object.assign({}, object1, {b: 22});
    
    console.log(object1);  // { a: 1, b: 2, c: 3 } 
    console.log(object2);  // { a: 1, b: 22, c: 3 } 
    

    Notice, this does not change the value of object1, it creates a new empty object as defined in the first parameter of Object.assign() and it adds further parameters to the empty object, and if it encounters the same key again then it updates the value of the key.

    In this way you can change one or even multiple values of an Object.

    A BETTER WAY

    Airbnb's JavaScript Style Guide() {} says that:

    Prefer the object spread operator over Object.assign to shallow-copy objects.

    // very bad
    const original = { a: 1, b: 2 };
    const copy = Object.assign(original, { c: 3 }); // this mutates 
    `original` ಠ_ಠ
    delete copy.a; // so does this
    
    // bad
    const original = { a: 1, b: 2 };
    const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, 
    b: 2, c: 3 }
    
    // good
    const original = { a: 1, b: 2 };
    const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
    

    You can see the full documentation here

提交回复
热议问题