Home > Mobile >  typescript/js comparing arrays of objects adding new key value
typescript/js comparing arrays of objects adding new key value

Time:07-15

My goal is to compare 2 objects if there is a match between object 1 and 2 using if they have the same id then insert new key value to object 1 which isConfirmed = true to each object that has a match;

Any idea guys ? I provided my current code below. Thanks.

#objects - original data

const object1 = [
    {
        "id": 10691,
        "city": "Morris",
    },
    {
        "id": 10692,
        "city": "NY",
]

const object2 = [
    {
        "id": 10691,
        "city": "Morris",
    {
        "id": 10500,
        "city": "JY",
    }
]

#ts code

  let result = object1.filter(o1 => object2.some(o2 => o1.id === o2.id));

#expected sample result

object1 = [
        {
            "id": 10691,
            "city": "Morris",
             "isConfirmed": true,

        },
        {
            "id": 10692,
            "city": "NY",
         }
    ]

CodePudding user response:

You can easily achieve the result using Set and map as:

const object1 = [
    {
        id: 10691,
        city: 'Morris',
    },
    {
        id: 10692,
        city: 'NY',
    },
];

const object2 = [
    {
        id: 10691,
        city: 'Morris',
    },
    {
        id: 10500,
        city: 'JY',
    },
];

const map = new Set(object2.map((o) => o.id));
const result = object1.map((o) =>
    map.has(o.id) ? { ...o, isConfirmed: true } : { ...o },
);

console.log(result);

CodePudding user response:

You can do it by using the snippet

let result = object1.map(o1 =>
  object2.some(o2 => o1.id === o2.id)
    ? {...o1, isConfirmed: true}
    : {...o1}
);

Check if object2 array has the object with any id from object1. If so, add isConfirmed: true to it.

const object1 = [
    {
        id: 10691,
        city: 'Morris',
    },
    {
        id: 10692,
        city: 'NY',
    },
];

const object2 = [
    {
        id: 10691,
        city: 'Morris',
    },
    {
        id: 10500,
        city: 'JY',
    },
];
let result = object1.map(o1 => object2.some(o2 => o1.id === o2.id) ? {...o1, isConfirmed: true} : {...o1});

console.log(result);

  • Related