简体   繁体   中英

converting to to key value pairs

This is the object I have

    const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ];
    let arr = [];


    for (const [key, value] of Object.entries(...upToPaidCost)) {
        arr.push({ key: key, value: value });
    }
    console.log(upToPaidCost)
    console.log(arr);

Expected output:

    [
        {
          key: "Labour Cost",
          value: 54000
        },
        {
          key: "Material Cost",
          value: 24900
        }
    ]

It shows only the first key value, the second is missing, what am I making wrong here?

The problem is, Object.entries takes a single object, and you've got an array of them. That's why you need two loops here:

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; let arr = []; for (const obj of upToPaidCost) { for (const [key, value] of Object.entries(obj)) { arr.push({key, value}); } } console.log(arr);

or two nested map s:

arr = upToPaidCost.flatMap(obj =>
    Object.entries(obj).map(([key, value]) => ({key, value})))

You can use the following code to do it

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; let arr = []; const updatedArr = upToPaidCost.map((item)=>{ return {"key":Object.keys(item)[0],"value":item[Object.keys(item)[0]]} }) console.log(updatedArr)

Test in this link https://replit.com/join/taxflvkp-gauthamjm007

As I can see, each item in the original array is an object. So you can do this way instead of iterating.

Besides, according to the expected output, value is a number. So you can cast from string to number like this.

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; const result = upToPaidCost.map(o => { const [key, value] = Object.entries(o)[0]; return {key, value: +value}; }); console.log(result);

I like my codes to be more readable. Alternative answer.

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; let arr = []; const final = upToPaidCost.map((item)=>{ const key = Object.keys(item)[0] return { key, value: item[key] } }) console.log(final)

Object.entries(...upToPaidCost) is equal to Object.entries({ 'Labour Cost': '54000' }) , so the result is wrong.

We need to combine the objects with the reduce method first:

const upToPaidCost = [{ "Labour Cost": "54000" }, { "Material Cost": "24900" }];
let arr = [];
const conbineObj = upToPaidCost.reduce(
  (res, item) => ({ ...res, ...item }),
  {}
);
for (const [key, value] of Object.entries(conbineObj)) {
  arr.push({ key: key, value: value });
}
console.log(upToPaidCost);
console.log(arr)

Why your snippet works like this?

In this line

for (const [key, value] of Object.entries(...upToPaidCost))

You are spreading upToPaidCost and then ask Object.entries to return it as an array-like.

so technically it's like this:

Object.entries({ 'Labour Cost': '54000' }, { 'Material Cost': '24900' })

as you see, you are passing 2 objects(arguments) to the Object.entries , which accept only one of them (the first one)

So this line will be interpreted like this

for (const [key, value] of [['Labour Cost': '54000']])`

How to correct the snippet?

you could replace Object.entries(...upToPaidCost) to Object.entries(upToPaidCost) so the Object.entries only get one simple argument

and then in the for loop, you can push each object to the arr

you can check it out here:

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; let arr = []; for (const [arrayindex, innerObject] of Object.entries(upToPaidCost)) { arr.push(innerObject); } console.log(upToPaidCost); console.log(arr);

As you can see, the values are still string, if you are up to turn them to the number, you can get the key and value and make new objects and push them to the arr like this:

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; let arr = []; for (const [upToPaidCostIndex, innerObject] of Object.entries(upToPaidCost)) { const key = Object.keys(innerObject)[0]; const value = Object.values(innerObject)[0]; arr.push({[key]: +value}); } console.log(upToPaidCost); console.log(arr);

Better solution

 const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ]; const upToPaidCosts = upToPaidCost.reduce((res, item) => ({...item, ...res}), {}); const arr = Object.entries(upToPaidCosts).map(([key, value]) => ({[key]: +value})) console.log(upToPaidCost); console.log(arr);

Here Object.entries(...upToPaidCost) remove...
Use... when you want to copy an object like: const x = {...upToPaidCost};
Or use Object.entries({...upToPaidCost}) for your case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM