我有一个变量列表,我将把它们组成一个带有键和值的数组。但是,在将它们作为数组之前,我想检查它们的值是否与特定字符串匹配,并将它们的键名称更改为其他名称。
让我们说这是变量列表
customer1 = "Jack", customerDate1 = "08/13/2021", customer2 = "Michael", customerDate2 = "01/01/2021", customer3 = "Luna",customerDate3 = "03/10/2021";
运行条件检查之前的数组将是
data = [{key1:"Jack", keyDate1:"08/13/2021",key2:"Michael", keyDate2:"01/01/2021",key3:"Luna", keyDate3:"10" }];
假设条件是:
customerName = "杰克";
我希望使用以下变量 (customer1,customer2,customer3) 交叉检查 customerName 变量,如果条件满足其中任何一个,则它们在数组中的键会更改:
例如,条件满足 customer1 然后 customer1 和 customerDate1 的键都更改为其他内容,变成类似
data = [{conditionMet1:"Jack", conditionDateMet1:"08/13/2021",key2:"Michael", keyDate2:"01/01/2021",key3:"Luna", keyDate3:"10" }];
我很感激任何帮助或指导。
像 alghoritm 一样有点棘手,但它有效:
let data = [{key1:"Jhon", keyDate1:"08/13/2021",key2:"Eric", keyDate2:"01/01/2021",key3:"Jack", keyDate3:"10" }];
let i = 1;
let result = [];
let explored = [];
data.forEach(x => {
let resultObj = {};
for (const [key, val] of Object.entries(x)) {
let newKey = key;
let newKeyDate = null;
if (val === "Jack") {
newKey = "conditionMet" + i;
newKeyDate = "conditionDateMet" + i;
}
if (!explored.includes(key)) resultObj[newKey] = val;
if (newKeyDate) {
resultObj[newKeyDate] = x["keyDate" + i];
explored.push("keyDate" + i)
}
if(!key.includes("Date")) i++;
}
result.push(resultObj)
})
console.log(result)
基本上,对于data
我探索的每个元素,entries
如果我找到了条件,我将添加conditionMet1
并添加conditionDateMet1
到对象,否则我在对象本身上找到的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句