gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:11:22 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 }

<小时/>

来自菲利普·科威施:

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/60088615/

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