Using Object key to make up a array

4215 views javascript
8

Considering follow code

const filterArray = ['a', 'b']
const objectToBeFilter = {
  a: {
    ab: 'ab',
    ac: 'ac',
    ad: 'ad'
  },
  b: {
    bb: 'bb',
    bc: 'bc',
    bd: 'bd'
  },
  c: {
    cb: 'cb',
    cc: 'cc',
    cd: 'cd'
  }
}

const resultWantToGet = [
  a: {
    ab: 'ab',
    ac: 'ac',
    ad: 'ad'
  },
  b: {
    bb: 'bb',
    bc: 'bc',
    bd: 'bd'
  }
]

FilterArray is a array to be used as a filter index, objectToBeFilter is a object which I want to handle. How to use filterArray to filter objectToBeFilter and then convert it to a array resultWantToGet?

answered question

You say you want an array, but the "array" you are showing has keys a and b, which is a syntax error. Do you want an array or new object?

The expected result is wrong

2 Answers

4

You can map by filterArray and spread into a new object:

const filterArray = ['a', 'b']
const objectToBeFilter = {
  a: {
    ab: 'ab',
    ac: 'ac',
    ad: 'ad'
  },
  b: {
    bb: 'bb',
    bc: 'bc',
    bd: 'bd'
  },
  c: {
    cb: 'cb',
    cc: 'cc',
    cd: 'cd'
  }
};
console.log({
  ...filterArray.map(key => ({ [key]: objectToBeFilter[key] }))
});

Or, if you don't want to create intermediate objects, use reduce:

const filterArray = ['a', 'b']
const objectToBeFilter = {
  a: {
    ab: 'ab',
    ac: 'ac',
    ad: 'ad'
  },
  b: {
    bb: 'bb',
    bc: 'bc',
    bd: 'bd'
  },
  c: {
    cb: 'cb',
    cc: 'cc',
    cd: 'cd'
  }
};
console.log(filterArray.reduce((a, prop) => {
  a[prop] = objectToBeFilter[prop];
  return a;
}, {}));

posted this
3

You can use reduce to loop and construct new object.

const filterArray = ['a', 'b']
const objectToBeFilter = {
  a: {
    ab: 'ab',
    ac: 'ac',
    ad: 'ad'
  },
  b: {
    bb: 'bb',
    bc: 'bc',
    bd: 'bd'
  },
  c: {
    cb: 'cb',
    cc: 'cc',
    cd: 'cd'
  }
}

const resultWantToGet = filterArray.reduce((c, v) => {
  if (objectToBeFilter[v]) c[v] = objectToBeFilter[v]; //Check if the key exist in objectToBeFilter, if it does, assign to the accumulator. 
  return c;
}, {})

console.log(resultWantToGet);

posted this

Have an answer?

JD

Please login first before posting an answer.