Search code examples
javascript-objects

How to Search or Compare values out of array of Objects in Javascript and return based on input


enter image description here

enter image description here

I have simply iterated through an array of objects. But I have no clue how I should compare the previous object values and display data along with current data. as shown in the image.

My Half solutions:

const dataSet = [{
    categoryId: 100,
    parentCategoryId: -1,
    name: "Business",
    keyword: "Money",
  },
  {
    categoryId: 200,
    parentCategoryId: -1,
    name: "Tutoring",
    keyword: "Teaching",
  },
  {
    categoryId: 101,
    parentCategoryId: 100,
    name: "Accounting",
    keyword: "Taxes",
  },
  {
    categoryId: 102,
    parentCategoryId: 100,
    name: "Taxation",
    keyword: "",
  },
  {
    categoryId: 201,
    parentCategoryId: 200,
    name: "Computer",
    keyword: "",
  },
  {
    categoryId: 103,
    parentCategoryId: 101,
    name: "Corporate Tax",
    keyword: "",
  },
  {
    categoryId: 202,
    parentCategoryId: 201,
    name: "Operating System",
    keyword: "",
  },
  {
    categoryId: 109,
    parentCategoryId: 101,
    name: "Small Business Tax",
    keyword: "",
  }
]

function solution(X) {
    // search your keyword 
    
    dataSet.map((item)=>{
        console.log("Item List: ", item);
        if (X === item.categoryId){
            const displayData = `\n\t ParentCategoryId : ${item.parentCategoryId} \n\t Name : ${item.name} \n\t Kewords : ${item.keyword}`;
           try{
               if(displayData) {
                   console.log("Your Searched Data:", displayData);
               }
           }catch (e) {
               return console.log ("error:", e);
           }
        }
    })
}

solution(201);


Solution

  • Below method will solve your problem.

    function solution(cId){
        let result = null;
        const getParentNode = function(parentId){
            const parentNode = dataSet.find(elm => elm.categoryId === parentId);
            if(parentNode && parentNode.keyword === ""){
                return getParentNode(parentNode.parentCategoryId);
            }
            return parentNode;
        }
        for(let i=0; i<dataSet.length; i++){
            if(dataSet[i].categoryId === cId){
                if(dataSet[i].keyword === "")
                    result = {...dataSet[i], keyword: getParentNode(dataSet[i].parentCategoryId).keyword};
                else
                    result = dataSet[i];
                break;
            }
        }
        return result;
    }