如何根据输入从 Javascript 和 return 中的对象数组中搜索或比较值

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

我只是遍历了一组对象。但我不知道我应该如何比较以前的对象值并显示数据与当前数据。如图所示

我的一半解决方案:

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

这可能对您有所帮助!

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

下面的方法可以解决您的问题。

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