Deltahost
Deltahost

Reputation: 117

Javascript: How to use array value as key?

console.log of an array ($myarray) returns this:

[ RowDataPacket { name: 'Foo', value: 1 },
  RowDataPacket { name: 'Bar', value: 3 } ]

How can I convert the array to make it possible to have the name available as key?

At the end console.log($myarray[Bar]) should return: 3

Upvotes: 0

Views: 69

Answers (2)

Lennholm
Lennholm

Reputation: 7460

What you want is to convert your array into an object. Use the reduce() function to iterate over each item in the array, process it and mutate the accumulator object that will be returned as the resulting object.

$myarray.reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 4

Nair Athul
Nair Athul

Reputation: 821

I think you can search using filter and return 0th element like

var array = [ { name: 'Foo', value: 1 },
  { name: 'Bar', value: 3 } ]

var result =  array.filter(i=>i.name=='Bar')[0]
console.log(result)

Upvotes: 0

Related Questions