Sun Tianyi
Sun Tianyi

Reputation: 93

Subset Json object in Javascript

Given an array of json object like this below, (the json object such as "name2" and "name4" will definitely have only one key-value)

[
  {
    abc: 123,
    id: '18263322',
    name: 'name1'
  },
  { name: 'name2' },
  {
    abc: 456,
    id: '18421634',
    name: 'name3'
  },
  { name: 'name4' }
]

How can I subset this so that I have two array of json objects:

[
  {
    abc: 123,
    id: '18263322',
    name: 'name1'
  },
  {
    abc: 456,
    id: '18421634',
    name: 'name3'
  }
]

and

[
  { name: 'name2' },
  { name: 'name4' }
]

Upvotes: 0

Views: 1025

Answers (1)

DecPK
DecPK

Reputation: 25408

You can use reduce here

const arr = [
  {
    abc: 123,
    id: "18263322",
    name: "name1",
  },
  { name: "name2" },
  {
    abc: 456,
    id: "18421634",
    name: "name3",
  },
  { name: "name4" },
];

const [single, multiple] = arr.reduce((acc, curr) => {
    Object.keys(curr).length === 1 ? acc[0].push(curr) : acc[1].push(curr);
    return acc;
  },[[], []]
);

console.log(single);
console.log(multiple);

You can also do something like

const [single, multiple] = arr.reduce((acc, curr) => {
    acc[Object.keys(curr).length === 1 ? 0 : 1].push(curr);
    return acc;
  },[[], []]);

using filter

const arr = [
  {
    abc: 123,
    id: "18263322",
    name: "name1",
  },
  { name: "name2" },
  {
    abc: 456,
    id: "18421634",
    name: "name3",
  },
  { name: "name4" },
];

const single = arr.filter((o) => Object.keys(o).length === 1);
const multiple = arr.filter((o) => Object.keys(o).length !== 1);

console.log(single);
console.log(multiple);

Upvotes: 1

Related Questions