How to replace/replace array keys

Asked

Viewed 79 times

1

I have 2 array’s (one that stores one person’s values and another that stores Keys/properties relative to this person) and would like to replace the 1 keys of these array to put as key in the other array, as follows:

let dataHead = ['nome', 'segundoNome', 'priSobrenome', 'segSobrenome'];
let dataBody = [
    { '0': 'Ikaro', '1': 'Fernando', '2': 'Sales dos', '3': 'Santos' },
    { '0': 'Ana', '1': 'Carolina', '2': 'Sales dos', '3': 'Santos' }
];

And I would like with the junction of these arrays to be as follows:

// 'nome': 'Ikaro', 'segundoNome': 'Fernando', 'priSobrenome': 'Sales dos', 'segSobrenome': 'Santos'

1 answer

2


Just go through your key array and go adding each key and value into a new object. That way:

let dataHead = ['nome', 'segundoNome', 'priSobrenome', 'segSobrenome'];
let dataBody = {'0': 'Ikaro', '1': 'Fernando', '2': 'Sales dos', '3': 'Santos'}

var novoObj = {};

for (i = 0; i < dataHead.length; i++){
    novoObj[dataHead[i]] = dataBody[i];
}

console.log(novoObj);

  • But then you changed the kind of dataBody man!

  • His dataBody didn’t make much sense, because the end result he wanted was with the values of the first object. What I did was just give a simplified, but if he wants to use that dataBody, just put the index 0 in front of [i].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.