2 回答
TA贡献1811条经验 获得超5个赞
使用Array.prototype.flatMap(). 如果您的浏览器或 Node.js 版本本身不支持此功能,您可以根据规范在下面包含一个简单的 polyfill :
if (!Array.prototype.flatMap) {
Object.defineProperty(Array.prototype, 'flatMap', {
configurable: true,
writable: true,
value: function flatMap (callback, thisArg = undefined) {
return this.reduce((array, ...args) => {
const element = callback.apply(thisArg, args);
if (Array.isArray(element)) array.push(...element);
else array.push(element);
return array;
}, []);
}
});
}
const data = [{name:'Movies',info:'category_name',content:[{name:'Interstellar',info:'category_data'},{name:'Dark Knight',info:'category_data'}]},{name:'Music',info:'category_name',content:[{name:'Adams',info:'category_data'},{name:'Nirvana',info:'category_data'}]},{name:'Places',info:'category_name',content:[{name:'Jordan',info:'category_data'},{name:'Punjab',info:'category_data'}]}];
const transformedArray = data.flatMap(({ content, ...o }) => [o, ...content]);
console.log(transformedArray);
TA贡献1856条经验 获得超17个赞
您可以使用reduce
method 和 spread syntax来做到这一点...
。
var data = [{"name":"Movies","info":"category_name","content":[{"name":"Interstellar","info":"category_data"},{"name":"Dark Knight","info":"category_data"}]},{"name":"Music","info":"category_name","content":[{"name":"Adams","info":"category_data"},{"name":"Nirvana","info":"category_data"}]},{"name":"Places","info":"category_name","content":[{"name":"Jordan","info":"category_data"},{"name":"Punjab","info":"category_data"}]}]
const result = data.reduce((r, {content, ...rest}) => {
r.push({...rest}, ...content)
return r;
}, []);
console.log(result);
您还可以使用concatandreduce代替扩展语法。
var data = [{"name":"Movies","info":"category_name","content":[{"name":"Interstellar","info":"category_data"},{"name":"Dark Knight","info":"category_data"}]},{"name":"Music","info":"category_name","content":[{"name":"Adams","info":"category_data"},{"name":"Nirvana","info":"category_data"}]},{"name":"Places","info":"category_name","content":[{"name":"Jordan","info":"category_data"},{"name":"Punjab","info":"category_data"}]}]
const result = data.reduce((r, {content, ...rest}) => r.concat(rest, content), []);
console.log(result);
添加回答
举报