通过检查对象内部字段的唯一性来创建对象的动态数组:Javascript

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

我需要根据检查字段的唯一性来创建对象的动态数组。我需要用这种格式的对象组成一个数组

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

我必须只获取一个具有字段“select”的对象,然后操作该对象。如果不存在,则需要创建 one.Here value 是一个字符串数组,在检查唯一性后将元素推入该数组。 .将传递一个输入字符串,将与值数组进行比较。假设“测试”是一个输入,那么数组应该是这样的,

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

如果 test1、test2 随后通过,则最终数组应如下所示

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

如果再次传递 test1,则不应将其推送,因为它已存在于数组中。比较应该不区分大小写

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

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