【发布时间】:2021-11-18 13:29:45
【问题描述】:
您好,我仍在研究我的 JS 技能,但我无法解决这个问题。我有两个数组,一个是电话联系人,另一个是消息。我正在尝试遍历每一个并返回一个自定义数组,其中包含一个基于联系人数组的新对象。
const myNumber = '69';
const contacts = [
{
phoneNumber: '420',
name: "Mike Smith",
favorite: false,
color: "orange"
},
{
phoneNumber: '360',
name: "John Smith",
favorite: true,
color: "green"
},
];
const messages = [
// ! from john to me
{
to: '69',
from: '360',
isRead: false,
time: new Date(),
owner: 0,
message: 'Hello there friend this is walker'
},
{
to: '69',
from: '360',
isRead: true,
time: new Date(),
owner: 1,
message: 'Hello there friend this is walker'
},
// ! from random number to me
{
to: '69',
from: '720',
isRead: false,
time: new Date(),
owner: 0,
message: 'Hello there friend from random person'
},
{
to: '69',
from: '720',
isRead: true,
time: new Date(),
owner: 1,
message: 'Hello there friend from random person'
}
];
我想返回一个如下所示的新消息数组...
const newMessages = [
// ! from John to me
{
to: '69',
from: '360',
isRead: false,
time: new Date(),
owner: 0,
message: 'Hello there friend this is John',
displayName: "John Smith"
},
{
to: '69',
from: '360',
isRead: true,
time: new Date(),
owner: 1,
message: 'Hello there friend this is John',
displayName: "John Smith"
},
// ! from random number to me
{
to: '69',
from: '720',
isRead: false,
time: new Date(),
owner: 0,
message: 'Hello there friend from random person',
displayName: '720',
},
{
to: '69',
from: '720',
isRead: true,
time: new Date(),
owner: 1,
message: 'Hello there friend from random person',
displayName: '720',
}
];
我们将显示名称属性添加到新消息对象。显示名称将返回联系人姓名,如果 "to" | “发件人”值 == 联系人“电话号码”。如果不是这种情况,默认情况下显示名称将返回消息“来自”值。
我真的不知道该怎么做。我尝试查看其他一些线程,但我没有运气。如果您有任何建议,请告诉我。另外,如果这个解释没有帮助,请告诉我!谢谢!
【问题讨论】:
-
欢迎来到 StackOverflow!请阅读How do I ask a good question? 和How to create a Minimal, Reproducible Example。在寻求帮助之前,您必须尝试解决自己的问题。如果您向我们提供您查看的线程的示例以及它们没有帮助的原因,这也会有所帮助
-
请提供足够的代码,以便其他人更好地理解或重现问题。
标签: javascript arrays sorting object filter