1

I have this array:

 array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},

         {key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]

I want to map "3", "5" and "4" (that are actually keys from another list inside the big list) from the values...something like this

array.map(function(d)
        {  return d.values."key";}));

In order to access the values 3, 5 and 4 I can use a for loop. However, there is a way to access values directly?

8
  • Does Object.keys() work? Commented May 10, 2018 at 15:15
  • Object.keys(d.values) Commented May 10, 2018 at 15:15
  • 1
    what do you mean by I want to map "3", "5" and "4" ? do you want a separate array/object for them ? Commented May 10, 2018 at 15:15
  • @GeorgeBailey to create a list with this 3 elements... I want to use this elements as domain of the axis. Object.keys(d.values) return only the elements from the last object of the list. Commented May 10, 2018 at 15:22
  • @CatalinVasilescu What is your expected output exactly? Commented May 10, 2018 at 15:25

2 Answers 2

2

Object.keys() will return an array of the keys of an object. Then you can use concat() to concatenate them.

array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},
         {key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}];
var result = [].concat(...array.map(d => Object.keys(d.values)));
console.log(result);

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

1 Comment

lol, I just typed [].concat(...array.map(d => Object.keys(d.values))) into my console to verify it worked before posting the answer.
0

Object.keys gives you array and as a result in map, you get something like

[[3],[4,5]]

You can flatten the return array to single array like

array.join(',').split(',');

var array = [{
        key: "6S",
        values: {
            3: [{
                Id: "1234a"
            }, {
                Id: "1234b"
            }]
        }
    },

    {
        key: "7S",
        values: {
            5: [{
                Id: "1534a"
            }],
            4: [{
                Id: "1534a"
            }]
        }
    }
];

 var newArray = array.map(o=>  Object.keys(o.values))
 
 console.log(newArray.join(',').split(','))

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.