0

I have an the following array:

var arr = [{name: "one name"}, {name: "second name"}, {name: "third name"}]

My goal is to have array like this:

var result = ["one name", "second name", "third name"]

I am playing around with something like this, just can't get it right:

var result = [];
for (var i=0; i<arr.length; i++) {
  result[arr[i]] = arr[i].NAME;
}

What I am misisng?

I am looking how to correct my code and use for loop instead of array map

user2917823
  • 199
  • 1
  • 9

3 Answers3

2

This is how to fix your code to do it with a for loop

var arr = [{name: "one name"}, {name: "second name"}, {name: "third name"}]
var result = [];
for (var i=0; i<arr.length; i++) {
  result[i] = arr[i].name;
}

console.log(result);

But using map would be more idiomatic javascript.

Ken
  • 4,367
  • 4
  • 28
  • 41
1

You could map the property values with Array#map.

var array = [{name: "one name"}, {name: "second name"}, {name: "third name"}],
    result = array.map(a => a.name);
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can simply use the .map() command to do something like this:

const result = arr.map(i => i.name)
AP.
  • 8,082
  • 2
  • 24
  • 33