Can I rename keys in objects in an array?

  • 0
    Good afternoon,
    tell me how you can bring the keys in the objects in the array to the same form, while the length of the objects is the same, but the keys can be different as an example:

    [
    {'key1' :  'Kiev', 'key2' :  'Ukraine'},
    {'134 ':  'Moskow', 'key2' :  'Rusian federation'},
    {'test2' :  'Warszaw', 'key2' :  'Poland'},
    {'_test' :  'Paris': 'test' :  'France'},
    ... итп
    ]

    Thanks a lot in advance !!!
    JavaScript Anonymous, Apr 4, 2019

  • 2 Answers
  • 0
    const keys = [ 'city', 'country' ];
    const newArr = arr.map(n => Object.fromEntries(Object.values(n).map((m, i) => [ keys[i], m ])));
    Anonymous

  • 0
    What type is it?

    const keys = [ 'city', 'country' ];
    arr.map((rawObj) => Object.values(rawObj).reduce((acc, value, index) => {
    acc[keys[index]] = value;
    return acc;
    }, {}));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!