Home > OS >  Javascript transform Object key to object values
Javascript transform Object key to object values

Time:08-18

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]);
});

CodePudding user response:

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]
    })
}

CodePudding user response:

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)

CodePudding user response:

Iterate over keys and map them to a new array:

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

CodePudding user response:

You can use Object.entries for this:

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

CodePudding user response:

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]
}));

CodePudding user response:

Just push the values in an array like so:

const want = [];
Object.keys(have).forEach(function (key) {
   want.push({day: key, count: have[key]});
});
  • Related