如何通过传递数组作为参数来获取数组中对象的子集

时间:2020-03-21 17:35:40

标签: javascript reactjs

我正在从API调用中接收对象数组作为响应数据。

data = [{obj1},{obj2},{obj3},{obj4},{obj5}]

obj1 = {
  prop1: 'value1',
  prop2: 'value2',
  prop3: 'value3',
}

我正在尝试使用一个数组,比方说:['prop2','prop3']过滤对象数组并返回对象子集的数组。

[{filteredObj1},{filteredObj2},{filteredObj3},{filteredObj4},{filteredObj5}]

filteredObj1 = {
  prop2: 'value2',
  prop3: 'value3'
}

依此类推...

最初尝试使用以下方法:

const arrayOfPropsIWant = ['prop1', 'prop2']

data.forEach((el) => {
  const filtered = (({ ...arrayOfPropsIWant }) => ({ ...arrayOfPropsIWant }))(el);
})

当我没有通过传递... arrayOfPropsIWant来进行结构分解时,这很有效,我显式地传递了道具(({prop1,prop2})

我正在尝试构建一个自定义的ReactJS挂钩,有什么方法可以实现呢?

4 个答案:

答案 0 :(得分:1)

尝试map

const data = [
 { prop1: 'value1', prop2: 'value2', prop3: 'value3' },
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'},
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'}
]

const result = data.map(({prop2, prop3})=>({prop2, prop3}))

console.log(result);

答案 1 :(得分:1)

您应该使用Array.map:

const data = [
 { prop1: 'value1', prop2: 'value2', prop3: 'value3' },
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'},
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'}
]

const arrayOfPropsIWant = ['prop1', 'prop2']

const filtered = data.map((elem) => {
    const out = {};
    arrayOfPropsIWant.forEach(prop => out[prop] = elem[prop]);
    return out;
   }
);

console.log(filtered);

答案 2 :(得分:1)

尝试一下,

const data = [
 { prop1: 'value1', prop2: 'value2', prop3: 'value3' },
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'},
 { prop1: 'value1', prop2: 'value2', prop3: 'value3'}
];

const props=['prop1','prop2']

const result = data.map((item)=>{
  Object.keys(item).map((key)=>{
    if(!props.includes(key))
      delete item[key];
  })
  return item;
})

console.log(result);

答案 3 :(得分:1)

您可以尝试以下方法:

const data = [
  { name: 'aaa', age: 10, id: 1 },
  { name: 'aab', age: 20, id: 2 },
];

const map = array => keys =>
  array.map(
    /** you should use 
    Object.fromEntries(
      Object.entries(item).filter(([key])=>keys.includes(key))
    )
    but beause Stack Overflow has not updated babel since years
    this will not work on SO code snippet
    **/
    item =>
      keys.reduce((result, key) => {
        result[key] = item[key];
        return result;
      }, {})
  );
const mapData = map(data);
console.log('id and name', mapData(['id', 'name']));
console.log('id and age', mapData(['id', 'age']));