简体   繁体   English

根据数组顺序过滤 Object 属性

[英]Filter Object property based on array with order of array

I have an array我有一个数组

const arr = ['a', 'b', 'd', 'c', 'e'];

The API sends this data API 发送此数据

const data ={a:'a', b:'b', c:'c', e:'e', f:'f'}

sometimes the keys are missing as well but the array keys should always be present in the final result.有时键也会丢失,但数组键应始终存在于最终结果中。

the output should be {a:'a', b:'b', d:'', c:'c', e:'e'} . output 应该是{a:'a', b:'b', d:'', c:'c', e:'e'} Please help me with ES6 and give me an explanation.请帮助我使用 ES6 并给我一个解释。 I am using reactjs16.9.我正在使用 reactjs16.9。 In this given case the object d is missing hence it should be initialised with "".在这个给定的情况下,object d 缺失,因此它应该用“”初始化。 In case If all the keys exist then extra keys from API should be removed.如果所有密钥都存在,则应删除 API 中的额外密钥。

You could iterate the keys and build a new object by using only wanted keys.您可以只使用想要的密钥来迭代密钥并构建新的 object。

Inside of the callback for mapping, the existence of the key is checked with the in operator and a conditional (ternary) operator ?: is used for getting either the value from the object or a placeholder ' ' for unknown properties.在映射回调内部,使用in运算符条件(三元)运算符?:检查键是否存在,用于从 object 或占位符' '获取未知属性的值。

The result is either an object with Object.fromEntries or a simple array.结果是带有 Object.fromEntries 的Object.fromEntries或简单数组。

 const keys = ['a', 'b', 'd', 'c', 'e'], data = {a: 'a', b: 'b', c: 'c', e: 'e', f: 'f' }, result = Object.fromEntries(keys.map(k => [k, k in data? data[k]: ' '])), onlyValues = keys.map(k => k in data? data[k]: ' '); console.log(result); console.log(onlyValues);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Perhaps this?也许这个?

Using ||使用 || to use space if no entry available如果没有可用的条目,则使用空间

 const arr = ['a', 'b', 'd', 'c', 'e']; const data = {a:'a', b:'b', c:'c', e:'e', f:'f'}; let newObj = {}; let newArr = []; arr.forEach(item => { newObj[item] = data[item] || " "; newArr.push( data[item] || " "); }) console.log(newObj); console.log(newArr);

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

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