Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - 如何获取javascript对象属性的子集(How to get a subset of a javascript object's properties)

Say I have an object:(说我有一个对象:)

elmo = { color: 'red', annoying: true, height: 'unknown', meta: { one: '1', two: '2'} }; I want to make a new object with a subset of its properties.(我想用其属性的子集创建一个新对象。) // pseudo code subset = elmo.slice('color', 'height') //=> { color: 'red', height: 'unknown' } How may I achieve this?(我该如何实现?)   ask by Christian Schlensker translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using Object Destructuring and Property Shorthand(使用对象分解和属性速记)

const object = { a: 5, b: 6, c: 7 }; const picked = (({ a, c }) => ({ a, c }))(object); console.log(picked); // { a: 5, c: 7 } From Philipp Kewisch:(来自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.(所有这些都可以在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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...