1

I would like to replace the key 'id' and it's value with the property of 'type' with a value of 'inc'or 'exp'. I also want to delete the property 'percentage' from the objects in the exp array. In the end I want to merge al the objects into one array.

This is what I did, it has the desired outcome but there must be a shortcut to achieve this, with less code and cleaner. Thanks!

const list = {
     exp: [
       { id: 0, value: 57, percentage: 12 },
       { id: 1, value: 34, percentage: 10 },
    ],
     inc: [
       { id: 1, value: 18 },
       { id: 1, value: 89 },
    ],
};

// Deep copy of list object
let newList = JSON.parse(JSON.stringify(list));

// Destructuring
const { exp, inc } = newList;

for (let obj of exp) {
  obj.type = "exp";
  delete obj.id;
  delete obj.percentage;
}

for (let obj2 of inc) {
  obj2.type = "inc";
  delete obj2.id;
}

//Spread operator
newList = [...newList.exp, ...newList.inc];
console.log(newList);


 

2 Answers 2

2

You could use flatMap in the support of Object.entries()

const list = {
  exp: [
    { id: 0, value: 57, percentage: 12 },
    { id: 1, value: 34, percentage: 10 },
  ],
  inc: [
    { id: 1, value: 18 },
    { id: 1, value: 89 },
  ],
};

const res = Object.entries(list).flatMap(([type, values]) =>
  values.map((value) => ({
    value: value.value,
    type: type,
  }))
);

console.log(res);

Step by step

A = Object.entries(list)

// -->

[
  [
    "exp",
    [
      { "id": 0, "value": 57, "percentage": 12 },
      { "id": 1, "value": 34, "percentage": 10 }
    ]
  ],
  [
    "inc",
    [
      { "id": 1, "value": 18 },
      { "id": 1, "value": 89 }
    ]
  ]
]
B = A.map(...)

// -->

[
  [
    { "value": 57, "type": "exp" },
    { "value": 34, "type": "exp" }
  ],
  [
    { "value": 18, "type": "inc" },
    { "value": 89, "type": "inc" }
  ]
]
C = B.flat()

// -->

[
  { "value": 57, "type": "exp" },
  { "value": 34, "type": "exp" },
  { "value": 18, "type": "inc" },
  { "value": 89, "type": "inc" }
]

flatMap is the combination of step B and C (.map then .flat)

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

Comments

1

If value is the only property you want:

const list = {
  exp: [
    { id: 0, value: 57, percentage: 12 },
    { id: 1, value: 34, percentage: 10 }
  ],
  inc: [
    { id: 1, value: 18 },
    { id: 1, value: 89 }
  ]
};

const newList = [];
const types = Object.keys(list);
types.forEach((type) => {
  list[type].forEach(({ value }) => {
    newList.push({ type, value });
  });
});

console.log(newList);
console.log(JSON.stringify(newList));

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.