skip to Main Content

I have forgotten most of what I learnt so treat ma as a novice. 🙁

I have an object of arrays returned from a database select statement as below :-

options:[{"breed":"bulldog"},{"breed":"labrador"}{"breed":"beagle"},{"breed":"dobermann"}]

Using javascript, how can I transpose this into an array as below :-

const breed ["bulldog","labrador","beagle","dobermann"];

The array will be used to populate a node-red dropdown menu.

Thanks for looking or advising.

I have tried split and map, but I cant seem to arrive at my required.
Maybe because I did not code it correctly.

2

Answers


  1. You’ll need to map() over the array, and then select the breed key of each object.

    const options = [{"breed":"bulldog"},{"breed":"labrador"},{"breed":"beagle"},{"breed":"dobermann"}];
    const breeds = options.map(o => o.breed);
    
    console.log(breeds);

    If you can’t use a hard-coded breed key, you can use Object.values() with flatMap():

    const options = [{"breed":"bulldog"},{"breed":"labrador"},{"breed":"beagle"},{"breed":"dobermann"}];
    const breeds = options.flatMap(o => Object.values(o));
    
    console.log(breeds);
    Login or Signup to reply.
  2. Object.values is probably the best way…

    const breeds = Object.values(options);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search