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
asked May 8, 2017 at 14:52
Deltahost
1171 gold badge3 silver badges12 bronze badges
2 Answers 2
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
answered May 8, 2017 at 14:55
Lennholm
7,5301 gold badge23 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
George
I've given you an upvote because your code does seem to work but could you add some detail on what it's doing and if possible why it works.
Pointy
Generally code-only answers are less helpful than they could be with added explanation.
Lennholm
Code first, explain later!
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)
answered May 8, 2017 at 14:57
Nair Athul
8219 silver badges21 bronze badges
Comments
lang-js
RowDataPacket? How are you constructing this array? Try providing some code in the form of a minimal reproducible example.