gpt4 book ai didi

javascript - 如何更新数组输出

转载 作者:行者123 更新时间:2023-12-02 22:15:05 24 4
gpt4 key购买 nike

输入是一个简单的对象数组(联系人)

输入:

[
{ name: "Mohan", phone: xxxxxx },
{ name: "Ramanujan", phone: xxxxxx },
{ name: "Rabindranath", phone: xxxxxx },
{ name: "Satyajit", phone: xxxxxx },
{ name: "Subhash", phone: xxxxxx },
{ name: "Bahadur", phone: xxxxxx }
];

我想要的输出:

[
{ title: "B", data: [{ name: "Bahadur", phone: xxxxxx }] },
{ title: "M", data: [{ name: "Mohan", phone: xxxxxx }] },
{
title: "R",
data: [
{ name: "Ramanujan", phone: xxxxxx },
{ name: "Rabindranath", phone: xxxxxx }
]
},
{
title: "S",
data: [
{ name: "Satyajit", phone: xxxxxx },
{ name: "Subhash", phone: xxxxxx }
]
}
];

非常感谢您投入的时间。谢谢。
即使是伪代码也可以。

最佳答案

你只需像这样映射你的数组:

const myArray = [
{name: 'Mohan', phone: 'xxxxxx'},
{name: 'Ramanujan', phone: 'xxxxxx'},
{name: 'Rabindranath', phone: 'xxxxxx'},
{name: 'Satyajit', phone: 'xxxxxx'},
{name: 'Subhash', phone: 'xxxxxx'},
{name: 'Bahadur', phone: 'xxxxxx'},
];
const output = myArray.map(item => {
return {
title: item.name.charAt(0),
data: [{name: item.name, phone: item.phone}],
};
});

顺便说一句,如果只有一项,数据不必是数组。数据:{name:item.name,phone:item.phone}也可以正常工作。

关于javascript - 如何更新数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59415648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com