根据指定的数组过滤对象道具 [英] Filter object props based on the specified array

查看:83
本文介绍了根据指定的数组过滤对象道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的对象

I have an object with the following structure

{ cardControlItem: 'Tidak',
  cardDirectUseItem: 'Tidak',
  kbUnspscUuid: '6a564b8e-2976-4fde-8759-7951970d7500',
  substoreUuid: '2f2b04bb-8b80-4b1f-b827-bf20311e31ee',
  cardDetailMin: 654,
  cardDetailMax: 65,
  cardDetailIncrement: 754,
  cardDetailPriceOverall: 4534,
  cardDetailPriceUnit: 0,
  ltMeasurementMinUuid: 'fddca37a-d0a3-40a4-8537-e84375b01601',
  ltMeasurementMaxUuid: '2bc6d7d2-5167-4459-9910-a65839008afd' }

我在数组中有一个键列表

and I have a list of keys in an array

['cardControlItem', 'cardDirectUseItem', 'kbUnspscUuid', 'substoreUuid', 'stockCardGroupUuid', 'stockCardBatchUuid']

如何根据指定的数组减少它

How do I reduce it according to the array specified

预期输出:

{ cardControlItem: 'Tidak',
  cardDirectUseItem: 'Tidak',
  kbUnspscUuid: '6a564b8e-2976-4fde-8759-7951970d7500',
  substoreUuid: '2f2b04bb-8b80-4b1f-b827-bf20311e31ee' }

P.S:我花了3个小时在StackOverflow上发现类似的问题.这类问题的正确标题是什么:D

P.S: I spent 3 hours spent to find similar problems on StackOverflow. What is the right title for this kind of problems :D

推荐答案

尝试此解决方案.我正在过滤obj(filter部分)中的属性,然后遍历存在的属性(reduce部分),然后将属性的值分配给新对象(acc).

Try this solution. I am filter the properties which are in the obj (filter part) and then iterate over the properties which exist (reduce part) and assign values of the properties into new object (acc).

const obj = { 
   cardControlItem: 'Tidak',
   cardDirectUseItem: 'Tidak',
   kbUnspscUuid: '6a564b8e-2976-4fde-8759-7951970d7500',
   substoreUuid: '2f2b04bb-8b80-4b1f-b827-bf20311e31ee',
   cardDetailMin: 654,
   cardDetailMax: 65,
   cardDetailIncrement: 754,
   cardDetailPriceOverall: 4534,
   cardDetailPriceUnit: 0,
   ltMeasurementMinUuid: 'fddca37a-d0a3-40a4-8537-e84375b01601',
   ltMeasurementMaxUuid: '2bc6d7d2-5167-4459-9910-a65839008afd' 
};

const keys = ['cardControlItem', 'cardDirectUseItem', 'kbUnspscUuid', 'substoreUuid', 'stockCardGroupUuid', 'stockCardBatchUuid'];

const mapped = keys.filter(key => obj.hasOwnProperty(key))
                   .reduce((acc, key) => { acc[key] = obj[key]; return acc }, {});

console.log(mapped);

这篇关于根据指定的数组过滤对象道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆