admin管理员组文章数量:1410682
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
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
-
1
use
Array.map()
function. Such questions were asked many times on SO – RomanPerekhrest Commented Dec 23, 2017 at 13:43 - how do you grant the order of the keys? – Nina Scholz Commented Dec 23, 2017 at 14:35
3 Answers
Reset to default 6Iterate 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);
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);
or use Object.entries
:
data = Object.entries(data).map(([name, values]) => ({name, values}));
本文标签: Add keyvalue pair in Javascript objectStack Overflow
版权声明:本文标题:Add key-value pair in Javascript object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744952452a2634158.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论