-2

I want to rename the keys in the object with the names of the array

let title = [
    'Total Cryptocurrencies',
    'Total Markets',
    'Total Exchanges',
    'Total Market Cap',
    'Total 24h Volume', 
];

var obj = {
    1: 5,
    2: 7,
    3: 0,
    4: 0,
    5: 0,
};

So in the end I want to have my object like this:

var obj = {
    'Total Cryptocurrencies': 5,
    'Total Markets': 7,
    'Total Exchanges': 0,
    'Total Market Cap': 0,
    'Total 24h Volume': 0,
};
David
  • 25
  • 1
  • 5
  • Does this answer your question? [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – codingmaster398 Mar 08 '22 at 11:22
  • Also, you can't guarantee the sort order of object properties when you iterate over them, so how would you know which array element matches the right object key? – Andy Mar 08 '22 at 11:23
  • 2
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Mar 08 '22 at 11:24
  • The code is only putting "" on the key and not renaming it with the names of the array – David Mar 08 '22 at 11:32

2 Answers2

0

You could do it with a for loop as follows.

let title = [
    'Total Cryptocurrencies',
    'Total Markets',
    'Total Exchanges',
    'Total Market Cap',
    'Total 24h Volume', 
];

var obj = {
    1: 5,
    2: 7,
    3: 0,
    4: 0,
    5: 0,
};

var newObj = {};

for(i = 0; i < title.length; i++) {
    newObj[title[i]] = obj[(i+1).toString()];
}

var obj = newObj;
Mike Irving
  • 1,480
  • 1
  • 12
  • 20
-2

Not sure if it the best solution but you can try

obj= title.reduce((prev, curr, idx) => {return {...prev, [curr]: obj[idx+1]} }, {});

Assuming obj's keys will be numbers will map perfectly with the title indexes

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '22 at 14:36