Home > front end >  Splitting js object based on new property
Splitting js object based on new property

Time:10-12

I'm trying to split this object based on a common new property 'subject'. There could be multiple subjects in a single object in the original data. But in the final data, it must have a single subject and the marks associated with it.

let x = {
  'Name': 'Ajay',
  'Maths': 0,
  'English': 26,
}

and the expected output is

let y = [{
  'Name' : 'Ajay',
  'Marks' : 0,
  'Subject' : 'Maths'
},{
  'Name' : 'Ajay',
  'Marks' : 26,
  'Subject' : 'English'
}]

It's basically splitting each object into multiple objects. Could anyone help me out with an approach to this?

I went with this approach in the end of iterating through the keys and skipping 'name' property.

for (let i of Object.keys(x)) {
let temp = {};
if (i === "Name") {
  continue;
} else {
  temp = {
    Name: x["Name"],
    Subject: i,
    Marks: x[i],
  };
}

CodePudding user response:

You could destructure the common property and map the other entries.

const
    convert = ({ Name, ...o }) => Object
        .entries(o)
        .map(([Subject, Marks]) => ({ Name, Subject, Marks })),
    data = { Name: 'Ajay', Maths: 0, English: 26 },
    result = convert(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

You can use object destructuring to extract name and then process remaining properties. Object.entries gives you key-value pairs:

let x = {
  'Name': 'Ajay',
  'Maths': 0,
  'English': 26,
};

const { Name, ...subjects } = x;

const result = Object.entries(subjects).map(([Subject, Marks]) => ({Name, Subject, Marks}));
console.log(result);

  • Related