I currently have an array of objects where each object has several properties. Example:
[
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
]
What would be the best way to convert this to an array of strings that contains the value from text? I had thought I might be able to do this using underscore.js:
headerText = _.pick(headerRow, 'text');
But I think that since the objects are in an array this will not work. My next idea is to just loop through each element in the array and push the text value to a new array, but i'm curious if anyone knows of a more elegant way to do this? Suggestions?
You're looking for Array#map:
var stringArray = headerRow.map(function(entry) {
return entry.text;
});
You don't even need Underscore, Array#map is part of ES5 and fully supported by V8, the JavaScript engine used by Node. Array#map calls the function you give it once for each entry in the array, and builds a new array from the return values of that function.
Or if you want to change the existing array, you can use Array#forEach:
headerRow.forEach(function(entry, index) {
headerRow[index] = entry.text;
});
Use _.map(headerRow, function(row) { return row.text; }). Array.map isn't available in IE < 9.
i'd use a foreach and just loop through it.
var jamie = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
var length = jamie.length,
element = [];
for (var i = 0; i < length; i++) {
element[i] = jamie[i].id;
// Do something with element i.
}
console.info(element);
This is a vanilla javascript version, which avoids using the not universally supported Array.map method.
// assign the array to a variable
var a = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
// loop through each item in the array, reassigning with it's text value
// not like this: for(i in a) a[i] = a[i].text
// but with a for loop based on the array length
var i;
for(i=a.length; i; i--){ a[i-1] = a[i-1].text; }
// check the results
console.log(a);
// ["test1", "test2"]