简体   繁体   English

我可以从对象中获取一些键值吗?

[英]Can I get some key values from an object?

let source = {a:1, b:2, c:3, d:4, e:5}



let result = (function make('a','c','e'){
    //Who can complete this code?
})()

console.log(result) // {a:1,c:3,e:5}

There are lots of different ways to do this but I would iterate over the object entries with reduce and only return those key/values where the key is one of the function arguments.有很多不同的方法可以做到这一点,但我会用reduce迭代对象条目,并且只返回那些键是函数参数之一的键/值。

 let source = { a: 1, b: 2, c: 3, d: 4, e: 5 }; function filterObj(...args) { return Object.entries(source).reduce((a, [k, v]) => { if (args.includes(k)) a[k] = v; return a; }, {}); } console.log(filterObj('a', 'c', 'e'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM