鍍金池/ 問答/HTML/ Js如何刪除數(shù)組中某一個元素?

Js如何刪除數(shù)組中某一個元素?

獲得一串數(shù)組,如下:

var data = [
{"id":"1","name":"小劉","age":"25"},
{"id":"2","name":"小華","age":"24"},
{"id":"3","name":"小佳","age":"27"},
{"id":"4","name":"小王","age":"24"},
{"id":"5","name":"小何","age":"22"},
];

刪除數(shù)組中age小于等于25歲的人,并返回新的數(shù)組:如下:

var data = [
{"id":"1","name":"小劉","age":"25"},
{"id":"3","name":"小佳","age":"27"},
];
回答
編輯回答
遺莣

filter了解一下

2017年6月11日 20:58
編輯回答
夏木

刪除小于或等于25的,返回新數(shù)組

function splice(){
    for(let i = 0;i<data.length;i++){
        if(parseInt(data[i].age)<26){
            data.splice(i,1);
            i--;
        }
    }
    console.log(data);
}
2018年6月10日 10:54
編輯回答
不舍棄

用underscore.js的filter的可以解決這個問題:

var data = [
            { "id": "1", "name": "小劉", "age": "25" },
            { "id": "2", "name": "小華", "age": "24" },
            { "id": "3", "name": "小佳", "age": "27" },
            { "id": "4", "name": "小王", "age": "24" },
            { "id": "5", "name": "小何", "age": "22" },
        ];
        var newData = _.filter(data, function(d){ return d.age > 25; })
2017年4月28日 03:25
編輯回答
薔薇花

謝謝一樓

var data = [ 
    {"id":"1","name":"小劉","age":"25"},
    {"id":"2","name":"小華","age":"24"},
    {"id":"3","name":"小佳","age":"27"},
    {"id":"4","name":"小王","age":"24"},
    {"id":"5","name":"小何","age":"22"},

];

new_data = data.filter(function(element, index) {
    return element['age'] >= 25; 
});

console.log(new_data);
2018年3月2日 01:58
編輯回答
柚稚
var data = [
            { "id": "1", "name": "小劉", "age": "25" },
            { "id": "2", "name": "小華", "age": "24" },
            { "id": "3", "name": "小佳", "age": "27" },
            { "id": "4", "name": "小王", "age": "24" },
            { "id": "5", "name": "小何", "age": "22" },
        ];

    var newData= data.filter(v=>v.age >= 25)
2017年7月17日 14:55
編輯回答
茍活
var data = [
            { "id": "1", "name": "小劉", "age": "25" },
            { "id": "2", "name": "小華", "age": "24" },
            { "id": "3", "name": "小佳", "age": "27" },
            { "id": "4", "name": "小王", "age": "24" },
            { "id": "5", "name": "小何", "age": "22" },
        ];

    var newData= [];
    var res = data.forEach(function (item, index, input) {
            if (parseInt(item["age"]) >= 25){
                newData.push(item);
            }
        })
    console.log(newData);
2017年11月14日 15:01
編輯回答
默念
var data = [
        {"id":"1","name":"小劉","age":"25"},
        {"id":"2","name":"小華","age":"24"},
        {"id":"3","name":"小佳","age":"27"},
        {"id":"4","name":"小王","age":"24"},
        {"id":"5","name":"小何","age":"22"},
    ];

    var data1 = []
    data.filter(function(e){
        if(e.age > 25){
            data1.push(e)
        }
    })
    console.log(data1)   //{id: "3", name: "小佳", age: "27"}
2018年9月6日 09:20