【问题标题】:How to create arrays based on array of objects value?如何根据对象数组的值创建数组?
【发布时间】:2021-05-30 11:36:29
【问题描述】:

我正在处理一项任务,我必须根据对象数组中的某些值创建数组。

输入数组:

const array = [{
        name: 'A',
        age: points: { x: 100, y: 107}
    },
    {
        name: 'B',
        age: points: { x: 210, y: 107}
    },
    {
        name: 'C',
        age: points: { x: 110, y: 107}
    },
    {
        name: 'D',
        age: points: { x: 230, y: 107}
    }
];

预期输出:

[
    [
        {
            name: 'A',
            age: points: { x: 100, y: 107}
        },
        {
            name: 'C',
            age: points: { x: 110, y: 107}
        }
    ],
    [
        {
            name: 'B',
            age: points: { x: 210, y: 107}
        },
        {
            name: 'D',
            age: points: { x: 230, y: 107}
        } 
    ]
]

注意:这里的条件值是动态的,例如在一定条件下跟随的点可以落在一个数组中,如果超出条件则形成新数组等等,可能有200+个对象在数组中。

万一出现新对象

{
    name: 'D',
    age: points: { x: 230, y: 107}
}

然后将形成一个新的对象数组,所有符合该条件的对象都应添加到该数组中。

请提出您的宝贵建议。

提前致谢。

【问题讨论】:

  • 请提供一些条件示例
  • 您是否事先了解所有可能的情况?

标签: javascript arrays javascript-objects


【解决方案1】:

您的问题并不完全清楚。据我猜测,你有一个对象数组,你需要存储一个空的结果数组。然后,逐个消耗“动态条件”,对原始数组使用过滤方法,并不断将结果添加到结果数组中。

这是一些伪代码:

let dataArray = [<your objects>];
let resultArray = [];
while(<dynamic condtions list is not empty>)
{
    resultArray.push(dataArray.filter(item=>{
        // write your filter logic based on your current dynamic condition here
        if(item satisifes condition)
           return true;
        else
           return false;
    }))
}
console.log(resultArray);

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2021-12-25
    • 2021-10-21
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多