Let say I have JSON object below:
var name = [
{
"first": "juan",
"last": "delaCruz"
},
{
"first": "james",
"last": "bond"
}
]
Can we use JSON.stringify to have the output:
juan, james
You might be looking for pluck, like in underscore. A basic implementation looks like this:
function pluck(collection, key) {
return collection.map(function(el) {
return el[key];
});
}
var name = [{
first: 'juan',
last:'dela Cruz'
}, {
first: 'james',
last:'bond'
}
];
var fullname = pluck(name, 'first');
Since the expected output doesn't appear to be valid JSON, you won't be able to get it with just JSON.stringify().
But, you could combine .map() and .join() to accomplish it:
var firsts = name.map(function (entry) {
return entry.first;
});
console.log(firsts.join(', ')); // juan, james
.map() is new with ECMAScript 5, so it'll be readily available in IE 9+ and other modern browsers. And, MDN includes a good polyfill to add it in older browsers.
JSON.stringifycan't produce the stringjuan, james, since that isn't legal JSON.