Reputation: 117
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
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
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