1

Hello I have a 2 variable with object and with a value of array object, in "test" and "test_2" i would like to merge the sku ("test") and feature ("test_2) based on id (as per below). What is the best way to merge, Im thinking of, for the test_2 I convert the feature into value array object ex: feature:[{id:xxx}] first and after that I do the merge, as I try it doesn't work. Hope anyone here can help me. Thank you

const test = 
    {
        sku: [
            {id:"282828282", link:"ksksks.com"},
            {id:"676867868", link:"lallaa.com"},
            {id:"543454554", link:"sssss.com"},
            {id:"345473663", link:"fdfsas.com"}
        ],
      
    }

const test_2 = 
{
        panels: [
            {id:"9328492847", feature: ['282828282']},
            {id:"6756734535", feature: ['543454554', '282828282']},
            {id:"6545353453", feature: []},
            {id:"4353567688", feature: []},
        ]
}

const test_3 = 
{

        panels: [
            {id:"9328492847", feature: [{id: '282828282', link:"ksksks.com"} ]},
            {id:"6756734535", feature: [{id: '543454554', link:"sssss.com"}, {id:'282828282',link:"ksksks.com"}]},
            {id:"6545353453", feature: []},
            {id:"4353567688", feature: []},
        ]

}

2 Answers 2

1
let skuSet = {};

for (let i = 0; i < test.sku.length; i++) {
    if (!skuSet[test.sku[i].id]) {
        skuSet[test.sku[i].id] = test.sku[i];
    }
}

for (let i = 0; i < test_2.panels.length; i++) {
    let current = test_2.panels[i];
    for (let j = 0; j < current.feature.length; j++) {
        if (skuSet[current.feature[j]]){
            current.feature[j] = skuSet[current.feature[j]];
        }
    }
}

console.log(JSON.stringify(test_2));

Let me know if you have any question regarding above logic.

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

1 Comment

hi garry thank you very much, this really solve my question
0
let skuMap = {};

test.sku.map((skuData) => { skuMap[skuData.id] = skuData })
test_2.panels.map((panelData) => {
  panelData.feature = panelData.feature.map((panelFeatureId) => skuMap[panelFeatureId])
})

Simple and fast

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.