如何根据value长度替换数组对象中的key标签?
实现方案
首先定义一个key映射表,把需要替换的原key和目标key一一对应,后续维护更方便:
const keyMap = { "Apple fruit": "Pizza shop", "Orange fruit": "Kfc shop", "Banana fruit": "Mcdonald shop", "Mango fruit": "fries shop" };
情况1:添加元素时直接处理
如果你是在push新元素到this.testItem时就要应用规则,可以在构造对象时直接判断处理:
// 假设testlabel是原key,testvale是对应的value const processedKey = testvale.length > 15 ? keyMap[testlabel] || testlabel : testlabel; this.testItem.push({ key: processedKey, value: testvale, }); console.log(this.testItem);
这里的|| testlabel是为了兼容原key不在映射表中的情况,避免出现undefined,直接保留原key。
情况2:对已有的testItem数组批量处理
如果已经有完整数组,需要批量更新所有元素的key,有两种实现方式:
方式一:生成新数组(推荐,不污染原数据)
this.testItem = this.testItem.map(item => { const newKey = item.value.length > 15 ? keyMap[item.key] || item.key : item.key; return { ...item, key: newKey }; }); console.log(this.testItem);
方式二:直接修改原数组
this.testItem.forEach(item => { if (item.value.length > 15) { item.key = keyMap[item.key] || item.key; } }); console.log(this.testItem);
验证结果
用你提供的示例数组测试,处理后最终数组为:
[ { "key": "Pizza shop", "value": "12123124344234234" }, // value长度17>15,替换key { "key": "Orange fruit", "value": "234352342332525" }, // value长度15,保留原key { "key": "Mcdonald shop", "value": "235235235235235235235" }, // value长度20>15,替换key { "key": "Mango fruit", "value": "235325235235235" } // value长度15,保留原key ]
内容的提问来源于stack exchange,提问作者guru
相关产品推荐
相关产品推荐

