Home > Net >  How to modify response using for loop
How to modify response using for loop

Time:11-07

I use postman call my api and here is the response.

I want to modify this object key into "id" and value is auto increment(1,2,3....), the value of original key( "amount 100~1000": 2) as "count" like expect to get down below.

data = {
        "amount 100~1000": 2,
        "amount 1001~2000": 4,
        "amount 2001~3000": 1,
        "amount 3001~4000": 2,
}

here is what i tried, i really don't know how to do this using for loop (or maybe forEach is better way?)

const x = Object.values(data[0])

let id = 1;
let count;
let arr = [];
for (let index = 0; index < x.length; index  ) {

    id  

    const obj = { id: index }
    arr.push(obj)
}
console.log(arr);// [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]

expect to get:

{
    "id":1, // amount 100~1000
    "count": 2,
},
{
    "id":2, // amount 1001~2000
    "count": 4,
},
{
    "id":3, // amount 2001~3000
    "count": 1,
},
.
.
.

CodePudding user response:

Re-edit: After the comments and follow-up questions I am adding a solution that will keep the values in the array sorted by the input data's keys. I am not sure this is what you intend but just for the sake of completeness.

const input = data[0];
const keys = Object.keys(input);
const output = [];
keys.sort((a, b) => a.localeCompare(b, { numeric: true })).forEach((key, idx) => {
    output.push({id: idx 1, count: input[key]})
})
console.log(output);

CodePudding user response:

You can implement this with Javascript Object built-in function Object.keys() or Object.values by simply looping them together:

const data = {
        "amount 100~1000": 2,
        "amount 1001~2000": 4,
        "amount 2001~3000": 1,
        "amount 3001~4000": 2,
}

const modifiedData = []

for (let i = 0; i < Object.keys(data).length; i  ) {
    modifiedData.push({id: i   1, count: Object.values(data)[i] })
}

console.log(modifiedData)

CodePudding user response:

Here's my solution to your question:

let data = {
        "amount 100~1000": 2,
        "amount 1001~2000": 4,
        "amount 2001~3000": 1,
        "amount 3001~4000": 2,
}

let list = []

let dataValuesList = Object.values(data)

for(let i = 1; i <= dataValuesList.length;i  ){
    list.push({
        id: i,
        count: dataValuesList[i-1]
    })
}

console.table(list)

  • Related