Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1478
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

var data = {
    \'PropertyA\': 1,
    \'PropertyB\': 2,
    \'PropertyC\': 3
};

Is it poss

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 06:22

    I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.

    For illustration, let's say we have an array named person with objects inside:

     let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]
    

    So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.

    Person.map((obj)=>({...obj,['Language']:"EN"}))
    

    The Person array now would become like this:

    Person = [{id:1, Name: "John", Language:"EN"}, 
    {id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]
    

提交回复
热议问题