Javascript 中的子集 Json 对象

Subset Json object in Javascript

给定一个像下面这样的 json 对象数组,(json 对象如“name2”和“name4”肯定只有一个键值)

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

我如何对其进行子集化,以便我有两个 json 对象数组:

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

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

你可以在这里使用reduce

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);

你也可以这样做

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

使用过滤器

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);