Home > Mobile >  Returning a particular property of an object from an array of objects
Returning a particular property of an object from an array of objects

Time:11-23

My array of objects looks something like this

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

I want to return an object/array that looks something like this

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

I tried mapping this array but I am unable to get the desired result and I am wondering what am I missing. Any help appreciated, thanks!

CodePudding user response:

You might need something like this:

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

You can play with it in this TypeScript playground

CodePudding user response:

You can do this:

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

Will return:

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