Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename Key in JS Object with values from another array

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,
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading