0

I have this object array:

var materials=[{sample:"A21"},{sample:"A22"},{sample:"A23"}];

The target is to create an new array replacing "sample" name with its corresponding value...

Result: var materials2=[{A21:"A21"},{A22:"A22"},{A23:"A23"}];

is this possible?

i've tried below loop passing key as string but without any luck!

for(i=0; i<materials.length; i++){

materials2.push({"'"+materials[i].sample+"'":materials[i].sample})

}

Any help will be appreciated! Thanks!

George Gotsidis
  • 426
  • 4
  • 15
  • The problem was actually accessing property value with the most optimal way. In my case, testing code performance also was important. The other correct approaches already answered did pin-point the subject but @Nina Scholz gave an answer that it was time efficient in ms execution. Since there is no for loop but internal map function. – George Gotsidis Nov 04 '19 at 13:08

1 Answers1

3

You could map the value with a computed property name.

var materials = [{ sample: "A21" }, { sample: "A22" }, { sample: "A23" }],
    result = materials.map(({ sample }) => ({ [sample]: sample }));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392