假设我有一个对象:

{
  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,所以扩散操作符是可用的。


当前回答

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

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>
    );
});

其他回答

只是现代JS的另一个解决方案,没有外部库。

我在玩“解构”功能:

Const raw = { Item1: {key: 'sdfd', value: 'sdfd'}, Item2: {key: 'sdfd', value: 'sdfd'}, Item3:{键:'sdfd',值:'sdfd'} }; var myNewRaw = (({item1, item3}) => ({item1, item3}))(raw); console.log (myNewRaw);

如果你可以使用ES6语法,我发现最干净的方法是:

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

const { item2, ...newData } = data;

现在,newData包含:

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

或者,如果你将键存储为字符串:

const key = 'item2';
const { [key]: _, ...newData } = data;

在后一种情况下,[key]被转换为item2,但由于您使用的是const赋值,因此需要为赋值指定一个名称。_表示丢弃值。

更普遍的:

const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...

这不仅将您的操作减少到一行程序,而且还不需要知道其他键是什么(那些您想要保留的键)。

一个简单的效用函数是这样的:

function removePropFromObject(obj, prop) {
  const { [prop]: _, ...rest } = obj
  return { ...rest }
}
const filteredObject = Object.fromEntries(Object.entries(originalObject).filter(([key, value]) => key !== uuid))

我很惊讶居然没有人提出这个建议。它非常干净,非常明确地告诉你想要保留哪些键。

const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filterObject = ({a,b,c}) => ({a,b,c})
const filteredObject = filterObject(unfilteredObject)

或者如果你想要一个脏的眼线笔:

const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filteredObject = (({a,b,c})=>({a,b,c}))(unfilteredObject);

基于以下两个答案:

https://stackoverflow.com/a/56081419/13819049 https://stackoverflow.com/a/54976713/13819049

我们可以:

const original = { a: 1, b: 2, c: 3 };
const allowed = ['a', 'b'];

const filtered = Object.fromEntries(allowed.map(k => [k, original[k]]));

哪个更干净更快:

https://jsbench.me/swkv2cbgkd/1