简体   繁体   English

将一个对象的属性和值提取到一个新的 object

[英]Pluck an object's properties and values into a new object

I want a nice small one liner to use an array, for example ['postcode','town'] , and then pluck just these properties from a larger object.我想要一个漂亮的小衬里来使用数组,例如['postcode','town'] ,然后从更大的 object 中提取这些属性。

So this:所以这:

const fields = ['postcode','town'];
const obj = {
    name: 'test',
    postcode: 'SS2 5JJ',
    town: 'Somewhere',
    other: 'info'
}

Would become this:会变成这样:

const filtered = {
    postcode: 'SS2 5JJ',
    town: 'Somewhere',
}

I did find this however I have mis-understood it I believe:我确实找到了这个但是我误解了它我相信:

const fields = ['postcode','town'];
Object.keys(fields).map(e => fields[e])

What is the best way to do this?做这个的最好方式是什么?

You could use Array.reduce你可以使用Array.reduce

 const fields = ['postcode', 'town']; const obj = { name: 'test', postcode: 'SS2 5JJ', town: 'Somewhere', other: 'info' }; const filteredObj = fields.reduce((acc, cur) => Object.assign(acc, { [cur]: obj[cur] }), {}); console.log(filteredObj);

Maybe:或许:

let res = Object.fromEntries(Object.entries(obj).filter(e => fields.includes(e[0]))

You can map your array fields to [key, value] which will create an array of [key, value] pairs.您可以将数组fields map 设置为[key, value] ,这将创建一个[key, value]对数组。 Once you have this array, you can use Object.fromEntries() to build your object for each key-value pair:拥有此数组后,您可以使用Object.fromEntries()为每个键值对构建 object:

 const fields = ['postcode','town']; const obj = { name: 'test', postcode: 'SS2 5JJ', town: 'Somewhere', other: 'info' }; const res = Object.fromEntries(fields.map(key => [key, obj[key]])); console.log(res);

"Best" is of course a subjective concept. “最佳”当然是一个主观的概念。 But I think that the reduce function is the cleanest way of doing it.但我认为减少 function 是最干净的方法。 That way there is no need to chain together different functions.这样就不需要将不同的功能链接在一起。

const filtered = fields.reduce((prev, key) => ({[key]: obj[key], ...prev}), {});

 const fields = ['postcode','town']; const obj = { name: 'test', postcode: 'SS2 5JJ', town: 'Somewhere', other: 'info' } const newObj = {}; Object.keys(obj).forEach(key => { if (fields.includes(key)) { newObj[key] = obj[key]; } }); console.log(newObj);

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

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