javascript - Filter array of objects - erase last word in the string
问题描述
I have an array of objects:
[
{
barcode: ""
description: "META AM 29 XX Edition Large"
description2: ""
group: "COM20"
},
{,
barcode: ""
description: "META AM 29 TEAM Large"
description2: ""
group: "COM20"
}
]
I want to get rid of the last word in the description. So the result would be:
[
{
barcode: ""
description: "META AM 29 XX Edition"
description2: ""
group: "COM20"
},
{,
barcode: ""
description: "META AM 29 TEAM"
description2: ""
group: "COM20"
}
]
I am using filter, but I don't understand why it doesn't work:
var filtered = data.filter((val) => {
return val.description.replace(/\w+[.!?]?$/, '');
})
console.log(filtered)
The log is the exactly same array without any change.
解决方案
Try this
let data = [{
barcode: "",
description: "META AM 29 XX Edition Large",
description2: "",
group: "COM20"
},
{
barcode: "",
description: "META AM 29 TEAM Large",
description2: "",
group: "COM20"
}
]
let result = data.map(ele => {
let lastword = ele.description.lastIndexOf(" ");
ele.description = ele.description.substring(0, lastword);
return ele;
});
console.log(result)
推荐阅读
- mysql - 计算Golang中数据库的查询数?
- java - 为什么输出保持相同的输出?
- r - 如何将多个df列相乘
- bash - 以特定格式格式化日志
- python - 当时间数据已被结算为索引时,如何绘制时间相关数据?
- javascript - 如何处理来自“不透明”类型的获取响应?
- firebase - 使用 FutureBuilder 时异步加载两个依赖流
- oracle - 要在 BI 报表中显示的 Oracle Unifier 图像数据,图像数据只显示一个数字
- javascript - 使用 jquery 删除动态创建的行并绑定/更新现金总额
- android - RecyclerView 从后端 api 加载 10000+ 图像