简体   繁体   中英

Mapping key and value to new keys in Javascript

Array of dictionaries should be converted simpler form.

 data = [{A:1},{B:2},{C:3}] 
 data = {A: 1, B: 2}
 data = ["0":{ A : 1, B : 2 , C : 3}]

Both are completely different datasets. I'm trying to map it also like below format. The above should become like

 data = [
  {
    name: "A",
    y: 1
  },
  {
    name: "B",
    y: 2
  },
  {
    name: "C",
    y: 3
  }
];

I tried this following approach but it's wrong

name = {}
data.forEach(function(k,x){
    return name['name'] = k , name["y"] = x 
})

Please suggest me a better approach.

map each object's entries to extract the key and the value, and return an object with name and y keys:

 const data = [{A:1},{B:2},{C:3}] const output = data.map(item => { const [name, y] = Object.entries(item)[0]; return { name, y }; }); console.log(output); 

You yould could chekc the data format and if it is not an array, build one and reduce the array by taking the objetcs and create for each key/value a new object for the result set.

 function simple(data) { return (Array.isArray(data) ? data : [data]).reduce((r, o) => [...r, ...Object.entries(o).map(([name, y]) => ({ name, y }))], []); } console.log(simple([{ A: 1 }, { B: 2 }, { C: 3, D: 4 }])); console.log(simple({ A: 1, B: 2 })); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

If the keys (A, B, etc) are guaranteed to be unique throughout the array, then everything becomes simpler.

 const data = [{A:1},{B:2},{C:3}]; const merged = Object.assign({}, ...data); const newData = Object.entries(merged) .map(([name, y]) => ({ name, y })); console.log(newData); 

However, if the keys aren't guaranteed unique, then refer to CertainPerformance's answer.

I would say, use Object.keys() which is widly supported

 let data = [{A:1},{B:2},{C:3}]; data = Object.assign({}, ...data); data = Object.keys(data).map(key => ({ name: key, y: data[key] })); console.log(data); 

you can implement like this

  var data = [{A:1},{B:2},{C:3}]; var reformattedArra = data.map(obj => { let val = {}; val.name = Object.keys(obj)[0]; val.y = obj[Object.keys(obj)[0]]; return val; }) console.log(JSON.stringify(reformattedArra)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM