Reputation: 45
I have an object in Javascript. I want to add key-value pair in it.
var data = {
Country1: '20',
country2: '30',
country3: '40',
country4: '45'
};
It should look like,
var data = {
{name: 'country1', values: '20'},
{name: 'country2', values: '30'},
{name: 'country3', values: '40'},
{name: 'country4', values: '45'},
};
I am looking for a solution where from a given object, country names will automatically fall into name
and values into values
Upvotes: 0
Views: 5023
Reputation: 191976
Iterate the Object#keys of the object with Array#map, and return an object in the format that you want.
Note: to ensure the order of the objects, you can sort the keys using String#localeCompare with the numeric: true
option.
var data = {
'Country1' : '20',
'country2': '30',
'country3': '40',
'country4' : '45'
};
var result = Object.keys(data)
.sort(function(a, b) { // if you need to ensure the order of the keys
return a.localeCompare(b, undefined, { numeric: true})
})
.map(function(key) {
return {
name: key,
value: data[key]
};
});
console.log(result);
Upvotes: 6
Reputation: 138257
or use Object.entries
:
data = Object.entries(data).map(([name, values]) => ({name, values}));
Upvotes: 0
Reputation: 222572
Use Objecy.Keys and forEach
to loop through the Objects,
var data = {
'Country1' : '20',
'country2': '30',
'country3': '40',
'country4' : '45'
};
var result = [];
Object.keys(data).forEach(key => {
result.push({'name':key,'value':data[key]});
});
console.log(result);
Upvotes: 0