0

I have an object that gives counts per day, and the date is the key. I would like to create a new object that has two properties (day and count) that uses the key:value pair.

This is the input format I have, and the structure I'm trying to achieve:

const have = {
    "2022/01/01":0, 
    "2022/01/02":10, 
    "2022/01/03":12, 
    "2022/01/04":6, 
    "2022/01/05":8
};

const want = [
        {day:"2022/01/01",count:0},
        {day:"2022/01/02",count:10},
        {day:"2022/01/03",count:12},
        {day:"2022/01/04",count:6},
        {day:"2022/01/05",count:8},
    ];

I've only gotten as far as printing each key and value to the log, but unsure how I can add these to a new object

let want = new Object();
Object.keys(have).forEach(function (key) {
    console.log(key);
    console.log(have[key]);
});
1
  • 1
    you could array.map() object's keys Object.keys(have).map(key => { return { day: key, count: have[key] } }) Commented Aug 18, 2022 at 9:53

6 Answers 6

1

Here you go

const have = {
  "2022/01/01": 0,
  "2022/01/02": 10,
  "2022/01/03": 12,
  "2022/01/04": 6,
  "2022/01/05": 8
};
const want = Object.keys(have).map((key) => ({
  day: key,
  count: have[key]
}));

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

Comments

1

You can try with array.map by taking up the object entries like,

const have = {
    "2022/01/01":0, 
    "2022/01/02":10, 
    "2022/01/03":12, 
    "2022/01/04":6, 
    "2022/01/05":8
};

const want = Object.entries(have).map(([day, count]) => ({
  day: day,
  count: count
}));

console.log(want)

Comments

1

Iterate over keys and map them to a new array:

Object.keys(have).map(entry => { return { date: entry, count: have[entry]}})

Comments

1

You can use Object.entries for this:

const want = Object.entries(have).map(([day, count]) => ({day, count}))

Comments

1

Just use Array.map function to get your required format returned:

const want = Object.keys(have).map((key) => ({
  day: key, count:have[key]
}));

Comments

0

Using a regular for..in loop, just traverse the keys, get the values and push to an empty array

let want = [];
for (let key in have) {
    want.push({
        day: key,
        count: obj[key]
    })
}

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.