-2

i have:

var first = { 0: true, 1: false, 2: true };

    var second = [
      { name: 'car', value: false },
      { name: 'bike', value: false },
      { name: 'moto', value: false }];

and i want to change the key of the first based on second like:

first = { car: true, bike: false, moto: true };
erik.hac
  • 111
  • 1
  • 9
  • 2
    Have you tried anything? This seems to be relatively simple problem – Rajesh Nov 10 '17 at 09:13
  • https://stackoverflow.com/questions/47214090/how-to-change-the-keys-in-one-object-with-javascript – Derek 朕會功夫 Nov 10 '17 at 09:17
  • 3
    Possible duplicate of [How to change the keys in one object with javascript?](https://stackoverflow.com/questions/47214090/how-to-change-the-keys-in-one-object-with-javascript) – caesay Nov 10 '17 at 09:17
  • I don't think you've put enough effort in trying to solve the question. It's too simple. – Carles Andres Nov 10 '17 at 09:26
  • @CarlesAndres It's not that simple, it requires knowledge of a `for..in` loop minimum, how would you solve this problem ? – doubleOrt Nov 10 '17 at 09:27
  • @Taurus You need to learn some basic Javascript before you can do it, of course, like [forEach](http://devdocs.io/javascript/global_objects/array/foreach). You know the saying "give a man a fish and he'll eat for one day, teach him how to fish and he'll eat forever". – Carles Andres Nov 10 '17 at 09:37

2 Answers2

0

I hope you tried something...

If I understood the issue, you can code:

var firstTemp = first;
for(var f in firstTemp){
    first[second[f].name]=first[f];
    first[f]=null;
}
firstTemp = null;
Stéphane Ammar
  • 1,454
  • 10
  • 17
0

You could iterate the array and update the object first. Then delete the used property.

var first = { 0: true, 1: false, 2: true },
    second = [{ name: 'car', value: false }, { name: 'bike', value: false }, { name: 'moto', value: false }];
    
second.forEach(function (o, i) {
    first[o.name] = first[i];
    delete first[i];
});

console.log(first);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks, i guess my problem was to acess the keys properties correctly, i see in your code you accessing in the right way. New guy in javascript, sorry and thanks. – erik.hac Nov 10 '17 at 09:31