为了账号安全,请及时绑定邮箱和手机立即绑定

如何从当前数组创建嵌套数组?

如何从当前数组创建嵌套数组?

温温酱 2022-06-09 19:46:42
如何根据数组中的值将此数组转换为新的嵌套数组当前阵列[{ name: 'John', review: 'Its great', book: 'Jungle Book'},{ name: 'Steve', review: 'Learned a lot', book: 'Coding Standards'},{ name: 'Chris', review: 'Love it', book: 'Coding Standards'},{ name: 'Jake', review: 'Would read again', book: 'Jungle Book'}]想做这个嵌套数组[{ book: 'Jungle Book', comment: [{   name: 'Jake',   review: 'Would read again'  },  {   name: 'John',   review: 'Its great'     }]},{ book: 'Coding Standards', comment: [{   name: 'Chris',   review: 'Love it'  },  {   name: 'Steve',   review: 'Learned a lot'     }]}]任何帮助或提示将不胜感激。
查看完整描述

2 回答

?
森栏

TA贡献1810条经验 获得超5个赞

您的预期结果不是有效的。我认为comment这里需要一个对象数组,例如:


const temp = [{name:"John",review:"Its great",book:"Jungle Book"},{name:"Steve",review:"Learned a lot",book:"Coding Standards"},{name:"Chris",review:"Love it",book:"Coding Standards"},{name:"Jake",review:"Would read again",book:"Jungle Book"}];


const res = Object.values(temp.reduce((ac, { name, review, book }) => {

  ac[book] = ac[book] || {book, comment: []}

  ac[book].comment.push({name, review})

  return ac;

}, {}));


console.log(res);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反对 回复 2022-06-09
?
九州编程

TA贡献1785条经验 获得超4个赞

const arr = [{

 name: 'John',

 review: 'Its great',

 book: 'Jungle Book'

},

{

 name: 'Steve',

 review: 'Learned a lot',

 book: 'Coding Standards'

},

{

 name: 'Chris',

 review: 'Love it',

 book: 'Coding Standards'

},

{

 name: 'Jake',

 review: 'Would read again',

 book: 'Jungle Book'

}];



const result = arr.reduce(function (r, a) {

    r[a.book] = r[a.book] || [];

    r[a.book].push(a);

    return r;

}, Object.create(null));


console.log(result);

你可以做我上面做的或者_.groupBy()从 lodash 使用。



查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号