JS按对象字段拆分对象数组
JS split array of objects by object field
我有一个令牌数组:
[
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
]
我想按等于 ,
:
的值拆分它们
[
[
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'}
],
[
{type: 'name', value: 'buzz'}
]
]
我应该怎么做?
您可以使用 Array.reduce()
来迭代项目。一共有三种情况:
- 该项目的值为
,
- 添加一个没有该项目的新子数组。
- 没有子数组 - 添加一个包含该项目的新子数组。
- 其余 - 将项目添加到最后一个子数组。
const data = [
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
];
const result = data.reduce((r, o) => {
if(o.value === ',') return [...r, []];
if(!r.length) return [[o]];
r[r.length - 1].push(o);
return r;
}, []);
console.log(result);
使用 forEach
let arr = [
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
]
let op = [];
let temp = [];
arr.forEach((e,i)=>{
if(e.value === ',' && temp.length){
op.push(temp);
temp =[];
} else {
temp.push(e);
}
});
if(temp.length) op.push(temp);
console.log(op);
我有一个令牌数组:
[
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
]
我想按等于 ,
:
[
[
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'}
],
[
{type: 'name', value: 'buzz'}
]
]
我应该怎么做?
您可以使用 Array.reduce()
来迭代项目。一共有三种情况:
- 该项目的值为
,
- 添加一个没有该项目的新子数组。 - 没有子数组 - 添加一个包含该项目的新子数组。
- 其余 - 将项目添加到最后一个子数组。
const data = [
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
];
const result = data.reduce((r, o) => {
if(o.value === ',') return [...r, []];
if(!r.length) return [[o]];
r[r.length - 1].push(o);
return r;
}, []);
console.log(result);
使用 forEach
let arr = [
{type: 'name', value: 'foo'},
{type: 'string', value: 'bar'},
{type: 'special', value: ','},
{type: 'name', value: 'buzz'}
]
let op = [];
let temp = [];
arr.forEach((e,i)=>{
if(e.value === ',' && temp.length){
op.push(temp);
temp =[];
} else {
temp.push(e);
}
});
if(temp.length) op.push(temp);
console.log(op);