简体   繁体   中英

Access key name of Object with dynamic key

I have this array of objects:

persons = [{Jon: 32}, {Paul: 35}, {Peter: 29}];

How can I get from the array above to the following array?

persons = [
  {name: 'Jon', age: 32},
  {name: 'Paul', age: 35},
  {name: 'Peter', age: 29},
];

const persons: {[key: string]: number}[] = [
           {Jon:32},
           {Paul:35},
           {Peter:29}
];

var a = persons
        .map(person => Object.keys(person)
                             .reduce(
                              (pv: {name?: string, age?: number}, cv: string) => {
                                 pv.name = cv;
                                 pv.age = person[cv];
                                 return pv;
                              },
                              {}));
console.log(a);

Another option which looks cleaner:

 var persons = [{ Jon: 32 }, { Paul: 35 }, { Peter: 29 }]; var list = persons.map(p => { return { name: Object.keys(p)[0], age: Object.values(p)[0] }; }); console.log(list);

 var persons = [{Jon: 32}, {Paul: 35}, {Peter: 29}]; var newPersons = []; persons.forEach(function(i){ var key = Object.keys(i)[0]; var item = {}; item[key] = i[key] newPersons.push(item); }) console.log(newPersons);

Succinct Typescript version

const p =[{ Jon: 32 }, { Paul: 35 }, { Peter: 29 }];

console.log( p.map(x=>({ name:Object.keys(x)[0],age: Object.values(x)[0] })) )

Code

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