[英]Pick values form an array of objects and create a new one : Javascript
I have an array of objects of the format:我有一个格式的对象数组:
input = [
{ key : "Test1", value: 25, total: 100},
{ key : "Test2", value: 35, total: 200},
{ key : "Test3", value: 45, total: 300},
{ key : "Test4", value: 55, total: 400},
{ key : "Test5", value: 65, total: 500}
]
I basically have to fetch some properties out of this and form a new array that should look something like this.我基本上必须从中获取一些属性并形成一个应该看起来像这样的新数组。
text
is equivalent to its text representation that is maintained in a separate object. text
等效于在单独的 object 中维护的文本表示。
textObj = { "Test1" : "Test1Eq" , "Test2" : "Test2Eq" , "Test3" : "Test3Eq" , "Test4" : "Test4Eq" , "Test5" : "Test6Eq" }
I just have to fetch count of Text1, Text4, Text 5
and return its text equivalent and its count in a new array.我只需要获取
Text1, Text4, Text 5
的计数并返回其等效文本及其在新数组中的计数。
Result结果
output = [
{ text : "Test1Eq", count: 25},
{ text : "Test4Eq", count: 55},
{ text : "Test5Eq", count: 65}
]
Method I tried我试过的方法
const res = input.map(item=>{
return{
text :textObj[item.key],
count: item.count
}
});
To find the count, you can use array#find
.要查找计数,您可以使用
array#find
。
const input = [ { key: "Test1", value: 25, total: 100}, { key: "Test2", value: 35, total: 200}, { key: "Test3", value: 45, total: 300}, { key: "Test4", value: 55, total: 400}, { key: "Test5", value: 65, total: 500} ], textObj = { "Test1": "Test1Eq", "Test2": "Test2Eq", "Test3": "Test3Eq", "Test4": "Test4Eq", "Test5": "Test6Eq" }, keys = ['Test1', 'Test4', 'Test5'], result = keys.map(key => ({ text: textObj[key], count: input.find(o => o.key === key)?.value })); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.