javascript - 我只想将文本附加到对象
问题描述
现在对于每个具有字符串“衬衫”的项目,我想将衬衫替换为“衬衫不可用
const inventory = [
{ line_item_id: "55412", item: "Shirt small", description: "" },
{ line_item_id: "55342", item: "shirt big full", description: "" },
{ line_item_id: "1124", item: "Pant Small",description: "",},
];
我希望它看起来像这样
const inventory = [
{ line_item_id: "55412", item: "Shirts are not available small", description: "" },
{ line_item_id: "55342", item: "Shirts are not available big full", description: "" },
{ line_item_id: "1124", item: "Pant Small",description: "",},
];
我使用了 map 函数,但它不包括未修改的行
我的代码
const test = convertedToJson.map((convertedToJson) => {
if (!!convertedToJson.item.match(/Shirt/i)) {
return convertedToJson.item + "Shirts are not available ";
}
});
console.log(test);
“我的输出”
const inventory = [
'Shirts are not available small'
'Shirts are not available big full'
];
解决方案
您可以使用地图和替换
const inventory = [{
line_item_id: "55412",
item: "Shirt small",
description: ""
},
{
line_item_id: "55342",
item: "shirt big full",
description: ""
},
{
line_item_id: "1124",
item: "Pant Small",
description: "",
},
];
const newVal = inventory.map((elem) => {
// checking if string contains shirt/Shirt
if (elem.item.toLowerCase().indexOf('shirt') !== -1) {
return {
...elem,
// case-insensitive replacement
item: elem.item.replace(/shirt/gi, "Shirts are not available")
}
} else {
return { ...elem
}
}
});
console.log(newVal)
推荐阅读
- javascript - 如何从 iFrame 中获取值
- java - 如何实现缓存系统?
- machine-learning - 如何构建 CNN 以正确分类四边形的边缘?
- javascript - 在反应中使用 HOC 时将道具渲染到包装组件
- api - Spotify API:端点当前正在播放的播客支持
- git - 当从终结器而不是 konsole 调用时,git push 不会提示我输入密码
- android - 尽管 proguard 处于停用状态,但真实广告未在发布模式下显示。可能是什么问题?
- c# - 如何将单选按钮插入 SQL Server 数据库?单选按钮位于 C# 的组框中
- raku - Perl 6:maxpairs 警告未定义值的字符串化
- java - 为什么 doGet 不运行 processRequest?