0

i have a big API answer with nested keys, that i don't want to add to my store as is. let's say i have an object

var apiResponse = {
  ... some fields
  lines: [{
  a: 'xxx',
  b: 'xxx',
  c: 'xxx',
  d: 'xxx',
  e: 'xxx'
}]
}

for now i am using

apiResponse.lines.map( ({a, b, e})  => ({a, b, e}) )

note there are more than 120 fields, and i may need to select more fields than i need today. so for code simplicity (or make it cleaner) i am trying to have an array lineFields

const neededFields = ['a', 'b' , 'e']
apiResponse.lines.map( ( { 'use my neededFieldsArray' } )  => ( { 'use my neededFieldsArray' }) ;

so when they day comes and i need to add fields , i just add in the neededFields array .

i used this approach with ODATA API before and it works like a charm because it accepts a string

var odataSelect= ['userName', 'Bio', 'ProfilePic']

var customUrl = `http://apiuri:someport/users?$select=${odataSelect.join(',')}`

i made a stackblitz template to test on. thank you

Amassuo
  • 31
  • 5
  • 2
    This doesn't look like a task for destructuring at all, it's the wrong tool. – ASDFGerte Jan 16 '20 at 14:58
  • @ASDFGerte how would you do it ? – Amassuo Jan 16 '20 at 15:02
  • 1
    You could [reduce the keys](https://stackoverflow.com/a/32184094) OR [use `Object.fromEntries()`](https://stackoverflow.com/a/56592365) – adiga Jan 16 '20 at 15:06
  • 1
    One way would be `neededFields.reduce((p, c) => (p[c] = original[c], p), {})`, but the dupe targets show many possibilities. – ASDFGerte Jan 16 '20 at 15:08
  • ok i will try both solutions and add an iteration to it , thanks – Amassuo Jan 16 '20 at 15:15
  • ```const filtered = ['id', 'name'].reduce((result, key) => { result[key] = orig[key]; return result; }, {}); ``` i ended up using this and added an iteration , works like intended, no repetition, – Amassuo Jan 16 '20 at 15:20

0 Answers0