[英]How to loop through an array of object to finding key values that includes same words-Javascript
I have an array of object with textnames我有一个带有文本名称的 object 数组
array= [{
text:"ABC",
someobj:{}
length: 3
},{
text:"XYZ",
someobj:{},
length: 4
},{
text:"TES",
someobj:{},
length: 2
},{
text:"ABC_VALUE",
someobj:{},length: 3
},{
text:"TES_VALUE",
someobj:{},length: 10
},{
text:"SME",
someobj:{},length: 39
},{
text:"SME_VALUE",
someobj:{}, length: 1
}
]
As you can see I have _VALUE
present in some text names.如您所见,我在某些文本名称中存在
_VALUE
。 I'm trying to get the total length of all the matching values, ie length of "ABC" + length of "ABC_VALUE"(6), similarly length of "SME_VALUE" + length of "SME" (40).我正在尝试获取所有匹配值的总长度,即“ABC”的长度+“ABC_VALUE”的长度(6),类似的“SME_VALUE”的长度+“SME”的长度(40)。
I tried with switch case and if condition.我尝试使用 switch case 和 if 条件。
function getVlaues(obj)
let length=0;
else if(obj.text.includes("SME")) {length += obj.length;}
else if (obj.text.includes("ABC")) {length += obj.length;}
else if (obj.text.includes("TES")) {length += obj.length;}
return length;
}
but this does not return me the total length of the 2 object.但这并没有返回 2 object 的总长度。 Any idea how to do this?
知道怎么做吗?
You can split text on _
and use the first value as key and calculate length for each key您可以在
_
上拆分文本并将第一个值用作键并计算每个键的长度
let array = [{text: "ABC",someobj: {},length: 3}, {text: "XYZ",someobj: {},length: 4}, {text: "TES",someobj: {},length: 2}, {text: "ABC_VALUE",someobj: {},length: 3}, {text: "TES_VALUE",someobj: {},length: 10}, {text: "SME",someobj: {},length: 39}, {text: "SME_VALUE",someobj: {},length: 1}] let final = array.reduce((op, inp) => { let text = inp.text.split('_', 1)[0] op[text] = op[text] || 0 op[text] += inp.length return op }, {}) console.log(final)
Or if you're sure the text
only differs by _value
in the end then you can replace that part and use as key或者,如果您确定
text
最后仅由_value
不同,那么您可以替换该部分并用作键
let array = [{text: "ABC",someobj: {},length: 3}, {text: "XYZ",someobj: {},length: 4}, {text: "TES",someobj: {},length: 2}, {text: "ABC_VALUE",someobj: {},length: 3}, {text: "TES_VALUE",someobj: {},length: 10}, {text: "SME",someobj: {},length: 39}, {text: "SME_VALUE",someobj: {},length: 1}] let final = array.reduce((op, inp) => { let text = inp.text.replace(/_value$/gi,'') op[text] = op[text] || 0 op[text] += inp.length return op }, {}) console.log(final)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.