0

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",
         }
    ]

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.