简体   繁体   中英

How to remove “integer” array from object in JavaScript

I got this input

    var input=[ "Axel",
                4,
                4.21,
                { name : 'Bob', age : 16 },
                { type : 'fish', model : 'golden fish' },
                [1,2,3],
                "John",
                { name : 'Peter', height: 1.90}          ];

and the Result must be this one

    [ { name : 'Bob', age : 16 },
      { type : 'fish', model : 'golden fish' },        
      { name : 'Peter', height: 1.90}            ];

Using Array.prototype.filter , only keep Objects which are not Arrays

var input = ["Axel",
    4,
    4.21,
    {name: 'Bob', age: 16},
    {type: 'fish', model: 'golden fish'},
    [1, 2, 3],
    "John",
    {name: 'Peter', height: 1.90}
];

input = input.filter(function (e) {
    return (typeof e === 'object') && !Array.isArray(e);
}); /*
[
    {"name": "Bob", "age": 16},
    {"type": "fish", "model": "golden fish"},
    {"name": "Peter", "height": 1.9}
]
*/

Try using array filter to remove the unwanted elements. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To remove all integers

var filteredList = input.filter(function(val) {
    return isNaN(val);
}):
/*
filteredList is now =
{ name: 'Bob', age: 16 },
{ type: 'fish', model: 'golden fish' },
[ 1, 2, 3 ],
'John',
{ name: 'Peter', height: 1.9 } ]
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM