【问题标题】:Returning a particular property of an object from an array of objects从对象数组中返回对象的特定属性
【发布时间】:2022-01-01 08:27:51
【问题描述】:

我的对象数组看起来像这样

const arr1 = [
  {person: {isPresent: true, isInsured: true, value:20}},
  {status: {isPresent: true, isInsured: true, value:20}},
]

我想返回一个看起来像这样的对象/数组

[
 {person: {value:20}},
 {status: {value:20}},
]

我尝试映射此数组,但无法获得所需的结果,我想知道我错过了什么。 任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 您的数据结构可能会被简化,因为您的对象只有一个属性 - 另一个对象。更容易让您的对象具有类型属性,取值“人”和“状态”。也许这会有所帮助。

标签: javascript arrays typescript javascript-objects


【解决方案1】:

你可能需要这样的东西:

interface Details {
  isPresent: boolean;
  isInsured: boolean;
  value: number;
}

interface Person {
  person: Details;
}

interface Status {
  status: Details;
}

type Tuple = [Person, Status];

const arr1: Tuple = [
  { person: { isPresent: true, isInsured: true, value: 20 } },
  { status: { isPresent: true, isInsured: true, value: 20 } },
];

const extractValue = ({ value }: Details) => ({ value });

const result = arr1.map(x => {
  if ('person' in x) {
    return { person: extractValue(x.person) };
  }
  if ('status' in x) {
    return { status: extractValue(x.status) };
  }
  return x;
});

console.log(result);

你可以在这个TypeScript playground玩它

【讨论】:

    【解决方案2】:

    你可以这样做:

    const arr1 = [
        {person: {isPresent: true, isInsured: true, value:20}},
        {status: {isPresent: true, isInsured: true, value:20}},
    ];
    
    const newArray = [];
    
    
    for (const val in arr1) {
    
        const keys = Object.keys(arr1[val]);
        keys.forEach((key, index) => {
            //console.log(key);
            //console.log(arr1[val][key]['value']);
            newArray.push({[key]: {value: arr1[val][key]['value']}});
    
        });
    }
    console.log(newArray);
    

    将返回:

    [ { person: { value: 20 } }, { status: { value: 20 } } ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2021-08-09
      • 2019-08-22
      • 2018-12-11
      • 1970-01-01
      • 2020-07-23
      相关资源
      最近更新 更多