-1

I am trying to compare two id's and append a property into existing local storage data. in for loop.

Here is the codepen that shows the sample data & logic.

Simply I am trying to check the id of var allcategorydatawithlevel with categorydata of var category_id & if these two match I want to append level property of the allcategorydatawithlevel to categorydata. Please take a look at the Codepen it contains data sample & logic which I have tried.

KarthikNayak98
  • 363
  • 3
  • 13
  • Your objects (or array with objects) seem to copied and pasted from the console and therefore they are syntactically incorrect. Please fix your code and make it run without errors. – Emiel Zuurbier Aug 04 '20 at 05:53
  • Ok, is their any way to fix that ? –  Aug 04 '20 at 05:56
  • There is. Check [this thread](https://stackoverflow.com/questions/10305365/javascript-chrome-how-to-copy-an-object-from-the-webkit-inspector-as-code) on how to copy an object from the console in chrome. – Emiel Zuurbier Aug 04 '20 at 06:01
  • Thankyou i have updated codepen –  Aug 04 '20 at 06:05
  • Please check the codepen –  Aug 04 '20 at 06:06

1 Answers1

0

I hope this help you :

  var categorydata = [
        { category_id: 2, name: "Default Category", position: 1 },
        { category_id: 3, name: "Clothing", position: 14597 },
        { category_id: 6, name: "Brands", position: 1 },
        { category_id: 8, name: "What's New", position: 1011 },
        { category_id: 12, name: "Dresses", position: 4456 },
        { category_id: 128, name: "Current Mood", position: 189 },
        { category_id: 138, name: "Mini", position: 13078 },
        { category_id: 630, name: "Kandi - Rave Clothing", position: 264 },
        { category_id: 1130, name: "Char Test Category", position: 99 },
        { category_id: 2443, name: "Sets", position: 163 },
        { category_id: 2657, name: "Club Exx Festival", position: 208 }
    
    ];
    var allcategorydatawithlevel = [
        { id: 1, level: 1 },
        { id: 2, level: 5 }
    ]

  var category = [];
    
    for (i = 0; i < allcategorydatawithlevel.length; i++) {
        for (x = 0; x < categorydata.length; x++) {
            if (allcategorydatawithlevel[i].id == categorydata[x].category_id) {
                category.push(allcategorydatawithlevel[i].level);
            }
        }
    }
    localStorage.setItem("category", JSON.stringify(category));
    console.log(JSON.stringify(category));

You can also use below code :

  allcategorydatawithlevel.forEach((item, index) => {
        categorydata.forEach((key, val) => {
            if (item.id === key.category_id) {
                category.push(item.level);
            }
        })
        localStorage.setItem("category", JSON.stringify(category));

    })
    console.log(JSON.stringify(category));
Elham Dabiri
  • 435
  • 2
  • 9