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

Share edited Sep 17, 2020 at 7:50 Ori Drori 194k32 gold badges238 silver badges229 bronze badges asked Dec 23, 2017 at 13:41 CodeleysCodeleys 452 silver badges6 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

Reset to default 6

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);

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