(javascript)是否可以将不同对象类型的数组拆分为一个对象类型的多个数组

(javascript) Is it possible to split an array of different object types into multiple arrays of one object type

所以我有一个包含具有不同属性的对象的数组,我想知道如何用整个数组具有相同属性的对象制作多个数组。

我想从这里开始

[
    {name:”test”, place:”country”},
    {name:”walkAndEat”, Long=100,Lat:15,Location:”place name”},
    {name:”test2”,place:”Europe”}
]

[
    {name:”test”, place:”country”},
    {name:”test2”,place:”Europe”}
]
[
    {name:”walkAndEat”, Long:100,Lat:15,Location:”place name”}
]

Javascript 对象不是固定类型,they are dynamic,这意味着您可以在执行期间更改它们。

JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed. That also means that you can have the same variable as different types:

var anything = arrayOfAnyOtherType[0]; 

有效...如果循环源数组并填充它,则可以为每个对象定义任何行为

如果您看到对象具有相同的属性,则可以将键作为(字符串化的)索引保存在集合对象中,并检查属性键是否已存在:

var arrcoll = {};
function add(o){
    var keys = JSON.stringify(Object.keys(o).sort());
    var arr = arrcoll[keys];
    if(arr)
        arr.push(o);
    else
        arrcoll[keys] = [o];
    return arr;
}

这可以即时完成,也可以在预先存在的阵列上完成,如此 Fiddle

所示

假设您有一个具有不同属性的对象列表,如下所示:

var placesOrPeople = [
    { name: 'Seymour Skinner', occupation: 'Principal' },
    { name: 'Kwik-E-Mart', lat: 23, long: 100 },
    { name: 'Sideshow Bob', occupation: 'Comic Foil' },
    { name: 'Flaming Tyre Yard', lat: 12, long: 88 },
    { name: 'Joe Quimby', occupation: 'Mayor' }
];

并且您希望将它们分类到单独的列表中,如下所示:

places = [
    { name: 'Kwik-E-Mart', lat: 23, long: 100 },
    { name: 'Flaming Tyre Yard', lat: 12, long: 88 }
];

people = [
    { name: 'Seymour Skinner', occupation: 'Principal' },
    { name: 'Sideshow Bob', occupation: 'Comic Foil' },
    { name: 'Joe Quimby', occupation: 'Mayor' }
];

您可以像这样使用内置的 Array.filter 命令:

var places = placesOrPeople.filter(function(currentPlaceOrPerson) {
    if (currentPlaceOrPerson.occupation !== undefined) {
        // it must be a person, since locations don't have occupations
        return true;
    } else {
        return false;
    }
});

var people = placesOrPeople.filter(function(currentPlaceOrPerson) {
    if (currentPlaceOrPerson.lat !== undefined && currentPlaceOrPerson.long !== undefined) {
        // it must be a place, since people don't have co-ordinates
        return true;
    } else {
        return false;
    }
});