有人可以帮我一些代码来拼接数组并推送到新数组吗?我有一个数组
someArray = [{
name: "Kristian",
lines: "2,5,10"
}, {
name: "John",
lines: "1,19,26,96"
}, {
name: "Kristian",
lines: "2,58,160"
}, {
name: "Felix",
lines: "1,19,26,96"
}];
我想将name =拼接到Kristian并推送到新数组
答案 0 :(得分:1)
您可以使用
filter()方法创建一个新数组,该数组包含所有通过提供的功能实现的测试的元素。
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。
var someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John", lines:"1,19,26,96"},{name:"Kristian", lines:"2,58,160"},{name:"Felix", lines:"1,19,26,96"}];
var res = someArray.filter((p,i) => {
if(p.name=="Kristian"){
someArray.splice(i, 1); //remove the mached object from the original array
return p;
}
});
console.log(res);
console.log('----------------');
console.log(someArray);
答案 1 :(得分:1)
您可以将.reduce()
方法与.splice()
一起使用:
let data = [
{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"}, {name:"Felix", lines:"1,19,26,96"}
];
let result = data.reduce((r, c, i, a) => {
if(c.name = 'Kristian')
r.push(a.splice(i, 1));
return r;
}, []);
console.log(result);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
您可以混合使用filter
和map
:
const filtered = someArray.filter(obj => obj.name !== "Kristian")
const newArray = someArray.map(obj => obj.name === "Kristian")
已过滤将删除这些项目,而map将使用删除的项目创建一个新数组