有一个数组,我想用map添加!每个项目
即:
之前->项目:[“球”,“书”,“笔”]
之后->物品:[“球!”,“书!”,“笔!”]
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
我在JS中尝试的方式:
const Plusitems = array.map(user => user.items+'!');
console.log(Plusitems);
答案 0 :(得分:3)
您可以使用map和destructing
const array = [{username: "john",team: "red",score: 5,items: ["ball", "book", "pen"]},{username: "becky",team: "blue",score: 10,items: ["tape", "backpack", "pen"]},{username: "susy",team: "red",score: 55,items: ["ball", "eraser", "pen"]},{username: "tyson",team: "green",score: 1,items: ["book", "pen"]},];
let op = array.map(({items,...rest})=>{
return {
...rest,
items: items.map( e=> e+'!')
}
})
console.log(op)
答案 1 :(得分:2)
您可以使用.map()
遍历输入数组,然后使用Object.assign()
创建更新的字符串数组。
const data = [
{username: "john", team: "red", score: 5, items: ["ball", "book", "pen"]},
{username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"]},
{username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"]},
{username: "tyson", team: "green", score: 1, items: ["book", "pen"]},
];
const result = data.map(o => Object.assign(o, {items: o.items.map(s => s + "!")}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
您可以为此使用Array#reduce
:
const array = [{username: "john",team: "red",score: 5,items: ["ball", "book", "pen"]},{username: "becky",team: "blue",score: 10,items: ["tape", "backpack", "pen"]},{username: "susy",team: "red",score: 55,items: ["ball", "eraser", "pen"]},{username: "tyson",team: "green",score: 1,items: ["book", "pen"]},];
const trArr = array.reduce((acc, ele) => {
ele['items'] = ele['items'].map((item) => `${item}!`);
acc.push(ele);
return acc;
}, []);
console.log(trArr);