Javascript循环并过滤掉null或空的数据

Javascript Loop and filter out the data thats null or empty

本文关键字:数据 null 循环 过滤 Javascript      更新时间:2023-09-26

我有一些数据,我需要过滤掉null或空的数据,并创建一个过滤的新数据列表。

在这种情况下,有时"names"数组是空的,所以我需要数据。

{
    "people": [
        {
            "id": "2",
            "description": "desc here",
            "names": [
                {
                    "name": "name here",
                },
                {
                    "name": "name here",
                }
            ],
            "other": "0"
        },
        {
            "id": "200",
            "description": "desc here",
            "names": null
            "other": "0"
        },
        {
            "id": "64",
            "description": "desc here",
            "names": [
                {
                    "name": "name here",
                },
                {
                    "name": "name here",
                }
            ],
            "other": "1"
        }
    ]
}

我该怎么做?

可以递归地迭代数组和对象,直到找到一个原语。然后检查并返回值。

function copy(object) {
    var o;
    if (Array.isArray(object)) {
        return object.reduce(function (r, a) {
            var v = copy(a);
            v.names !== null && v.names !== '' && r.push(v);
            return r;
        }, []);
    }
    if (object !== null && typeof object === 'object') {
        o = {};
        Object.keys(object).forEach(function (k) {
            o[k] = copy(object[k]);
        });
        return o;
    }
    return object;
}
var data = { people: [{ id: "2", description: "desc here", names: [{ id: "345", name: "name here", }, { id: "54", name: "name here", foo: "", }], other: "0" }, { id: "2", description: "desc here", names: null, other: "0" }, { id: "64", description: "desc here", names: [{ id: "87", name: "name here", }, { id: "53", name: "name here", }], other: "1" }] },
    result = copy(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

var newArray = oldArray.filter(function(v){return v!==''});
new_array=yourObject.people.filter(function(elem){
 return elem.names!==null && elem.names!==""
});