Dibish Dibish - 10 months ago 42
Javascript Question

Insert an item to array object using underscorejs

I want to insert an id in to an existing array of objects using underscorejs.

input array

var arr = [{name:"iPhone"}, {name:"Samsung"}];


expected output array

var arr = [{name:"iPhone", owner_id: "555"}, {name:"Samsung", owner_id: "555"}];


Tried following, its working but looking for a better way

devices = []
arr.forEach(function(data) {
var device = {};
device.owner_id = "555";
device.name= data.name;
devices.push(device )
})

Answer Source

No need to use underscore. Here is an easy way using the .map method. Each object returned inside the callback will be inserted into the devices array.

var devices = arr.map(function(data) {
    var device = {};
    device.owner_id = "555";
    device.name= data.name;

    return device;
})

If you console.log devices it will print (depending on data of course):

[{name:"iPhone", owner_id: "555"}, {name:"Samsung", owner_id: "555"}];