Object 过滤

我心飞翔 分类:javascript

1.根据key值过滤出对应项

function getKeyObject(targetObject, propsArray) {
    if (typeof (targetObject) !== "object" || !Array.isArray(propsArray)) {
        throw new Error("参数格式不正确");
    }
    const result = {};
    Object.keys(targetObject).filter(key => propsArray.includes(key)).forEach(key => {
        result[key] = targetObject[key];
    })
    return result;
}
 

image.png

2.根据value值过滤出对应项

function getValueObject(targetObject, propsArray) {
    if (typeof (targetObject) !== "object" || !Array.isArray(propsArray)) {
        throw new Error("参数格式不正确");
    }
    return Object.keys(targetObject).reduce(function(r, e) {
      if (propsArray.includes(targetObject[e])) r[e] = targetObject[e]
      return r;
    }, {})
}
 

image.png

3.过滤掉value为空的项

function getEmptyObject(targetObject) {
    if (typeof (targetObject) !== "object") {
        throw new Error("参数格式不正确");
    }
    const result = {};
    Object.keys(targetObject).filter(key => {
        if(targetObject[key]) result[key] = targetObject[key];
    })
    return result;
}
 

image.png

回复

我来回复
  • 暂无回复内容