【发布时间】:2021-04-10 04:48:30
【问题描述】:
现在对于每个具有字符串“衬衫”的项目,我想将衬衫替换为“衬衫不可用
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'
];
【问题讨论】:
-
这不是您运行代码时得到的输出。在
item中没有带有复数Shirts的.match(/Shirts/i),因此,它返回一个undefineds 的数组。另外,如果要替换属性,请使用forEach而不是map
标签: javascript node.js arrays json map-function