1

I have a dictionary structure as follows : data = { a : [5, 10], b : [1, 12] , c : [6, 7]}

I need to convert this to follows : [ a, 5, 10 ], [ b, 1, 12 ], [ c, 6, 7 ]

I've already tried using Object.entries(data), but it returned the data like : [a, [5, 10]], [b, [1, 12]]

How can i do this using JavaScript?

4 Answers 4

6

You could map the key/values in a new array.

var data = { a : [5, 10], b : [1, 12] , c : [6, 7]},
    result = Object.entries(data).map(([k, v]) => [k, ...v]);

console.log(result);

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

Comments

2

Another way:

const  data = { a : [5, 10], b : [1, 12] , c : [6, 7]};
const result = Object.entries(data).map(pair => pair.flat());
console.log(result);

Comments

1

So with Object.keys() and reduce() you can solve as the following:

const data = { a: [5, 10], b: [1, 12], c: [6, 7] };
const result = Object.keys(data).map(e => {
  return data[e].reduce((a, c) => {
    a.push(c);
    return a;
  }, Array.from(e));
});

console.log(result);

I hope that helps!

Comments

1
var dict = { 'a': 'aa', 'b': 'bb' };
var arr = [];

for (var key in dict) {
    if (dict.hasOwnProperty(key)) {
        arr.push( [ key, dict[key] ] );
    }
}

this might helps you out

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.