[removed] filter() for Objects

前端 未结 16 960
心在旅途
心在旅途 2020-11-22 15:23

ECMAScript 5 has the filter() prototype for Array types, but not Object types, if I understand correctly.

How would I implemen

16条回答
  •  遥遥无期
    2020-11-22 15:27

    How about:

    function filterObj(keys, obj) {
      const newObj = {};
      for (let key in obj) {
        if (keys.includes(key)) {
          newObj[key] = obj[key];
        }
      }
      return newObj;
    }
    

    Or...

    function filterObj(keys, obj) {
      const newObj = {};
      Object.keys(obj).forEach(key => {
        if (keys.includes(key)) {
          newObj[key] = obj[key];
        }
      });
      return newObj;
    }
    

提交回复
热议问题