Home > database >  Comparing property of object with property of another array
Comparing property of object with property of another array

Time:07-12

I am having difficulty comparing properties of two objects/arrays

First object

{
"62ac1c8d5b25ad28781a586d": {
    "selectedOption": 0
},
"62ac1c8d5b25ad28781a586e": {
    "selectedOption": 0
}}

Second Array

[
{
    "question_id": "62ac1c8d5b25ad28781a586d",
    "selected_ans": 0
},
{
    "question_id": "62ac1c8d5b25ad28781a586e",
    "selected_ans": 0
},
{
    "question_id": "62ac1c8d5b25ad28781a586f",
    "ans": 0
}

]

Kindly suggest how to compare the initial property of first object(example: 62ac1c8d5b25ad28781a586d) with the question_id property of second array and return only the matching question_id

CodePudding user response:

You can filter elements from secondArr using Set as:

const obj = {
    '62ac1c8d5b25ad28781a586d': {
        selectedOption: 0,
    },
    '62ac1c8d5b25ad28781a586e': {
        selectedOption: 0,
    },
};

const secondArr = [
    {
        question_id: '62ac1c8d5b25ad28781a586d',
        selected_ans: 0,
    },
    {
        question_id: '62ac1c8d5b25ad28781a586e',
        selected_ans: 0,
    },
    {
        question_id: '62ac1c8d5b25ad28781a586f',
        ans: 0,
    },
];

const keys = new Set(Object.keys(obj));
const result = secondArr.filter((o) => keys.has(o.question_id));
console.log(result);

CodePudding user response:

You could simply use the find method defined on the array prototype.

function compare(id, arr){
    return arr.find(arrObj => arrObj.question_id === id);
}

To find all the matching ids from the object present in the array, you could loop through the keys and call the compare function for those keys like this.

function compare(id, arr) {
    return arr.find(arrObj => arrObj.question_id === id);
}

const obj = {
    "62ac1c8d5b25ad28781a586d": {
        "selectedOption": 0
    },
    "62ac1c8d5b25ad28781a586e": {
        "selectedOption": 0
    }
}

const arr = [
    {
        "question_id": "62ac1c8d5b25ad28781a586d",
        "selected_ans": 0
    },
    {
        "question_id": "62ac1c8d5b25ad28781a586e",
        "selected_ans": 0
    },
    {
        "question_id": "62ac1c8d5b25ad28781a586f",
        "ans": 0
    }
]
const matchingObjects = [];
for (let key in obj) {
    const matchObject = compare(key, arr);
    if (matchObject) {
        matchingObjects.push(matchObject);
    }
}
console.log(matchingObjects);

  • Related