简体   繁体   中英

Add new property with default value to javascript array of objects

I want to add a new property to values called gender with a default value of "male". Is the only method to accomplish adding the property is to loop thru the array. Or is there a more efficient strategy?

var data = [];
data.push({id: 1, values: {"age":33,"name":"Duke"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
var obj;
for obj in data {
  obj.values.gender = "male";
}

So the data will be

data = [
   {id: 1, values: {"age":33,"name":"Duke","gender":"male"}},
   {id: 2, values: {"age":34,"name":"Dave","gender":"male"}}
];      

You could try OOP Javascript and use the prototype to add a property to all objects of that type:

function Person(age, name) {
    this.age = age;
    this.name = name;
}

var data = [];
data.push({id: 1, values: new Person(33, "Duke") });
data.push({id: 2, values: new Person(34, "Dave") });

Person.prototype.gender = 'male';

console.log(data[0].values.gender) // male

@Tom's answer is better if you know the property you want to add and it's not dynamic. My solution is better if the property you want to assign to all objects is unknown until runtime.

I am afraid to say you cannot avoid a for loop. However, I have created a comparison for you and you can think of the performance. As expected, a simple for loop is always faster. Take a look:

 var data = []; data.push({id: 1, values: {"age":33,"name":"Duke"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); data.push({id: 2, values: {"age":34,"name":"Dave"}}); function foreachFn(d){ d.forEach(function(el){ el.values.gender='male'; }); return d; } function simpleLoopFn(d){ for (var i = 0;i<d.length;i++){ d[i].values.gender = "male"; } } function mappingData(d){ let newdata = d.map(function(el) { el.values.gender = 'male'; }); } var t1 = 0, t2 =0; let foreachData=data; t1 = console.time('foreachFn') foreachFn(foreachData); t2 = console.timeEnd('foreachFn'); let simpleData= data; t1 = console.time('simpleLoopFn') simpleLoopFn(simpleData); t2 = console.timeEnd('simpleLoopFn'); let mappedData = data; t1 = console.time('mappingData') mappingData(mappedData); t2 = console.timeEnd('mappingData');

There is. You can work with objects and constructors to assign a default value to a property. Code speaks more than words:

var Person = (function () {
    function Person(age, name, gender) {
        this.age = age;
        this.name = name;
        this.gender = gender ? gender : "male";
    }

    return Person;
}());

var data = [];
data.push({ id: 1, values: new Person(33, "Duke") });
data.push({ id: 2, values: new Person(34, "Dave") });

Becomes:

data = [
    {
        id: 1,
        values: {
            "age": 33,
            "name": "Duke",
            "gender":"male"
        }
    },
    {
        id: 2,
        values: {
            "age": 34,
            "name": "Dave",
            "gender":"male"
        }
    }
]

You might even do the following to change the gender other than male:

data.push({ id: 2, values: new Person(35, "Jessica", "female") });

jsFiddle: https://jsfiddle.net/wtomcskr/1/

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