Rename Object Key in an array using javascript
Use the map
function:
var array = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];
var resultArray = array.map(function(elm) {
return { Name: elm[widget.seriesname], Data: elm[widget.dataname]};
});
const arr = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];
const resultArray = arr.map(elm => ({ Name: elm.id, Data: elm.name}));
console.log(resultArray);
EDIT: Just seen your angular tag - use angular's forEach:
var out = [];
angular.forEach(data, function (obj) {
out.push({
Name: obj.id,
Data: obj.name
});
});
Without angular:
For modern browsers, use array.map:
var out = data.map(function (obj) {
return {
Name: obj.id,
Data: obj.name
};
});
console.log(out);
And in older browsers:
var data = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];
var out = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
out.push({
'Name': data[key].id,
'Data': data[key].name
});
}
}
console.log(out);