0

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

3
  • 1
    There is an example of this exact scenario in Documentation Commented May 8, 2017 at 14:58
  • What is RowDataPacket? How are you constructing this array? Try providing some code in the form of a minimal reproducible example. Commented May 8, 2017 at 14:58
  • The RowDataPacket comes from the result of a mysql return. github.com/mysqljs/mysql Commented May 8, 2017 at 15:02

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Generally code-only answers are less helpful than they could be with added explanation.
Code first, explain later!
0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.