【问题标题】:Separate or split asociative objects into 2 arrays using javascript使用 javascript 将关联对象分离或拆分为 2 个数组
【发布时间】:2021-05-17 13:28:51
【问题描述】:

我有一个对象“成员”,它有键,每个键都有对象数组

var members = {
    'Father' : [
        {
            name: 'John Doe'
        }
    ],
    'Mother' : [
        {
            name: 'Jane Doe'
        }
    ],
    'Uncles': [
        {
            name: 'James Doe'
        },
        {
            name: 'Sam Smith'
        },
        {
            name: 'Mark Smith'
        }
    ],
    'Aunties': [
        {
            name: 'Mary Doe'
        },
        {
            name: 'Mae Smith'
        }
    ]
}

我想把它们分成两个数组

var allMembers = [];
var half = Math.ceil(Object.keys(members).length / 2);
var firstHalf = Object.keys(members).splice(0, 4);
var secondHalf = Object.keys(members).splice(4);
allMembers.push(firstHalf)
allMembers.push(secondHalf)

但是allMembers的结果是这样的:

[["Father", "Mother"], ["Uncles", "Aunties"]]

我想让它变成这样的结果:

0: [
   'Father' : [
        {
            name: 'John Doe'
        }
   ],
   'Mother': [
        {
            name: 'Jane Doe'
        }
   ]
],
1: [
   'Uncles': [
        {
            name: 'James Doe'
        },
        {
            name: 'Sam Smith'
        },
        {
            name: 'Mark Smith'
        }
    ],
    'Aunties': [
        {
            name: 'Mary Doe'
        },
        {
            name: 'Mae Smith'
        }
    ]
]

我怎样才能做到这一点?

这是小提琴:https://jsfiddle.net/mqk6bswu/

【问题讨论】:

  • 您想要的结果是无效的 JavaScript;数组有数字键;你需要一个数组中的两个对象(例如[{ Fathers: [], Mothers: [] }, { Uncles: [], Aunties: [] }]
  • 是的@HereticMonkey,我怎样才能做到这一点?
  • 这能回答你的问题吗? Javascript split object by key
  • 不是真的,但@adiga 已经回答了.. 谢谢!

标签: javascript arrays object


【解决方案1】:

您可以获取对象的entries 并将它们分成两部分,而不是获取密钥。在两个数组上使用Object.fromEntries() 得到一个包含两个对象的数组

const members={Father:[{name:"John Doe"}],Mother:[{name:"Jane Doe"}],Uncles:[{name:"James Doe"},{name:"Sam Smith"},{name:"Mark Smith"}],Aunties:[{name:"Mary Doe"},{name:"Mae Smith"}]},
      entries = Object.entries(members),
      half = Math.ceil(entries.length / 2),
      firstHalf = entries.splice(0, half),
      secondHalf = entries, // remaining
      allMembers = [firstHalf, secondHalf].map(Object.fromEntries);

console.log(allMembers)

【讨论】:

    【解决方案2】:

    获得[{ Fathers: [], Mothers: [] }, { Uncles: [], Aunties: [] }] 最直接的方法是手动映射它。例如;

    const result = [{Fathers: members.Fathers, Mothers: members.Mothers }, { Uncles: members.Uncles, Aunties: members.Aunties}];
    

    更高级的解决方案是使用Object.entries 并动态映射数据。

    【讨论】:

    • 谢谢.. 我喜欢@adiga 的回答,它更有活力
    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2019-12-28
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多