0

This is the object I have:

years = {1924:2, 1934: 10, 2010: 4}

I would like to transform this into:

years = [{year: 1924, items: 2}, {year: 1934, items: 10}, {year: 2010, items: 4}]

This is the code I came up with so far (which obviously doesn't work):

var years2 = {};

for (var i = 0; i < years.length; ++i) {
    years2.push({ years: [$key] })
};

I am stuggling to find the right way to access the unnamed keys and map these into their own objects.

(I am still learning JS and I know this is basics, but somehow cannot get my head around it.. )

0

2 Answers 2

1

You can create key value pairs from the object with Object entries and map them to new array

const years = {1924:2, 1934: 10, 2010: 4}


const ans = Object.entries(years).map(([key,value]) => {
  return {year: key, items: value}
})

console.log(ans);

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

2 Comments

Code dumps are not useful answers. Say what you did, and why, before posting.
Thanks! that works and slowly start to make sense to me too :)
1

You can get entries, then convert to object with map

const years = {1924:2, 1934: 10, 2010: 4}
const result = Object.entries(years).map(([year, items]) => ({year: year, items: items}))
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.