gpt4 book ai didi

javascript - 如何获取 javascript 对象属性的子集

转载 作者:数据小太阳 更新时间:2023-10-29 05:37:11 25 4
gpt4 key购买 nike

假设我有一个对象:

elmo = { 
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};

我想用它的一部分属性创建一个新对象。

 // pseudo code
subset = elmo.slice('color', 'height')

//=> { color: 'red', height: 'unknown' }

我怎样才能做到这一点?

最佳答案

使用对象解构和属性简写

const object = { a: 5, b: 6, c: 7  };
const picked = (({ a, c }) => ({ a, c }))(object);

console.log(picked); // { a: 5, c: 7 }


来自 Philipp Kewisch:

This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

let unwrap = ({a, c}) => ({a, c});

let unwrap2 = function({a, c}) { return { a, c }; };

let picked = unwrap({ a: 5, b: 6, c: 7 });

let picked2 = unwrap2({a: 5, b: 6, c: 7})

console.log(picked)
console.log(picked2)

关于javascript - 如何获取 javascript 对象属性的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com