假设我有一个对象:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}

我想通过过滤上面的对象来创建另一个对象这样我就有了。

 {
    item1: { key: 'sdfd', value:'sdfd' },
    item3: { key: 'sdfd', value:'sdfd' }
 }

我正在寻找一种干净的方法来实现这一点使用Es6,所以扩散操作符是可用的。


当前回答

没有什么之前没有说过的,但是把一些答案结合到ES6的一般答案中:

Const raw = { Item1: {key: 'sdfd', value: 'sdfd'}, Item2: {key: 'sdfd', value: 'sdfd'}, Item3:{键:'sdfd',值:'sdfd'} }; const filteredKeys = ['item1', 'item3']; const filtered = filteredKeys .reduce((obj, key) =>({…Obj, [key]: raw[key]}), {}); console.log(过滤);

其他回答

利用ssube的答案。

这是一个可重用的版本。

Object.filterByKey = function (obj, predicate) {
  return Object.keys(obj)
    .filter(key => predicate(key))
    .reduce((out, key) => {
      out[key] = obj[key];
      return out;
    }, {});
}

叫它use

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

var filtered = Object.filterByKey(raw, key => 
  return allowed.includes(key));
});

console.log(filtered);

ES6箭头函数的美妙之处在于,你不必将allowed作为参数传入。

上面的许多解决方案都重复调用Array.prototype.includes来处理raw中的每个键,这将使解决方案为O(n·m)(其中n是对象中键的数量,m是允许列表的长度)。

这可以通过使用一个允许的Set来避免,但是遍历允许的键并将它们复制到一个初始为空的对象中会得到非常简单,可读的代码,即O(m):

Const raw = { Item1: {key: 'sdfd', value:'sdfd'}, Item2: {key: 'sdfd', value:'sdfd'}, Item3:{键:'sdfd',值:'sdfd'} }; Const allowed = ['item1', 'item3']; Const filtered = {}; For(允许的const键){ If (key in raw) filter [key] = raw[key]; } console.log(过滤);

如果你想避免复制继承的属性,你也可以使用raw. hasownproperty (key)来代替key in raw。

另一种方法是使用Array.prototype.forEach()作为

Const raw = { item1: { 关键:“sdfd”, 价值:“sdfd” }, 第二条:{ 关键:“sdfd”, 价值:“sdfd” }, item3: { 关键:“sdfd”, 价值:“sdfd” } }; Const allowed = ['item1', 'item3', 'll ']; var finalObj = {}; 允许的。forEach(allowedVal => { 如果原始[allowedVal]) finalObj[allowedVal] = raw[allowedVal] }) console.log (finalObj)

它只包含原始数据中可用的那些键的值,从而防止添加任何垃圾数据。

没有什么之前没有说过的,但是把一些答案结合到ES6的一般答案中:

Const raw = { Item1: {key: 'sdfd', value: 'sdfd'}, Item2: {key: 'sdfd', value: 'sdfd'}, Item3:{键:'sdfd',值:'sdfd'} }; const filteredKeys = ['item1', 'item3']; const filtered = filteredKeys .reduce((obj, key) =>({…Obj, [key]: raw[key]}), {}); console.log(过滤);

在循环过程中,当遇到某些属性/键时,不返回任何内容,并继续执行其余的:

const loop = product =>
Object.keys(product).map(key => {
    if (key === "_id" || key === "__v") {
        return; 
    }
    return (
        <ul className="list-group">
            <li>
                {product[key]}
                <span>
                    {key}
                </span>
            </li>
        </ul>
    );
});