简体   繁体   中英

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

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'} . Please help me with ES6 and give me an explanation. I am using reactjs16.9. In this given case the object d is missing hence it should be initialised with "". In case If all the keys exist then extra keys from API should be removed.

You could iterate the keys and build a new object by using only wanted keys.

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.

The result is either an object with Object.fromEntries or a simple array.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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