Search code examples
javascriptarraysecmascript-6ecmascript-5ecmascript-2016

Create a dynamic array of objects by checking uniqueness of a field inside object : Javascript


I have a requirement of creating a dynamic array of objects, based on checking the uniqueness of a field. I need to form an array with objects of this format

[
  { text : "select", label: "select", value: []},
  { text: "abc" , label: "abc" , value: [1,2,3] }
]

I have to just fetch an object that has field "select" and then manipulate that object. If it is not present, then need to create one.Here value is a string array to which elements are pushed into after checking the uniqueness. .There will be an input string passed, against which the value array will be compared. Suppose "test" is an input , then array should look like,

{ text : "select", label: "select", value: ["test1"]}

If test1, test2 are passed subsequently then the final array should look like

{ text : "select", label: "select", value: ["test1", "test2", "test3"]}

If again test1 is passed, it should not be pushed as it is already present in the array. Comparing should be case insensitive

function checkAndPush(arr, inputVal){
     let finalArr = [];
     if (arr?.some((item) => item.text === "select")) { 
         finalArr = [...new Set(arr.map((item) => item.text.toLocaleLowercase() === inputVal.toLocaleLowercase())
     } else {
          finalArr.push({ text : "select", label: "select", value: [inputVal]});
     }
     console.log(finalArr);
}


Solution

  • // I guess this is what you trying to do...?
    
    // so you have this obj_list
    const obj_list = [
        { text: "select", label: "select", value: ["test1", "test2", "test3"] },
        { text: "abc", label: "abc", value: [1, 2, 3] }
    ];
    
    // something like button, pressed and input is "test1"
    function buttonOnclick(input = "test1") {
    
        // try to get obj that text is "select"
        let target  = obj_list.find(obj=> obj.text == "select");
    
        // if not found, creat it and push in to obj_list
        if(!target) {
            target = { text: "select", label: "select", value: [] };
            obj_list.push(target);
        }
    
        // check value and save result 
        target.value = checkAndPush(target.value, input);
    }
    
    function checkAndPush(arr, inputVal) {
    
        // creat empty array if not exist for some reason
        if (!arr) arr = [];
    
        // use input array as set
        let current_arr_set = new Set(arr);
    
        // make value check case insensitive
        inputVal = inputVal.toLocaleLowerCase();
    
        // if inputVal not in set, push it to arr
        if (!current_arr_set.has(inputVal)) arr.push(inputVal);
    
        // return edited arr
        return arr;
    }