gpt4 book ai didi

javascript - 如何在 JavaScript 中使用 id 查找唯一值?

转载 作者:行者123 更新时间:2023-12-05 09:01:13 26 4
gpt4 key购买 nike

如何在 JavaScript 中查找带有 id 的唯一值?现在我得到的只是值(value)。

我得到:-

[
"Care One",
"Care Two"
]

我需要:-

[
{
"Source_ID": 1,
"SourceName_CR": "Care One"
},
{
"Source_ID": 2,
"SourceName_CR": "Care Two"
}

]

我的代码:-

const body = [
{
Field_ID: 1,
FieldName_CR: "First Name",
Source_ID: 1,
SourceName_CR: "Care One"
},
{
Field_ID: 2,
FieldName_CR: "Last Name",
Source_ID: 1,
SourceName_CR: "Care One"
}, {
Field_ID: 3,
FieldName_CR: "Phone",
Source_ID: 2,
SourceName_CR: "Care Two"
},
{
Field_ID: 4,
FieldName_CR: "Email",
Source_ID: 2,
SourceName_CR: "Care Two"
}, ];

console.log([...new Set(body.map(item => item.SourceName_CR))]);

最佳答案

Set 在这里不起作用,因为您想要删除重复的对象 - 但对象不能以这种方式相互比较。只做 .map(item => item.SourceName_CR) 也没有意义,因为那样你只会得到字符串(例如 Care Two)而不是整个对象想要。

按要删除重复数据的源 ID 对源名称进行分组,然后将生成的对象的条目转换为所需的结构。

const body = [
{
Field_ID: 1,
FieldName_CR: "First Name",
Source_ID: 1,
SourceName_CR: "Care One"
},
{
Field_ID: 2,
FieldName_CR: "Last Name",
Source_ID: 1,
SourceName_CR: "Care One"
}, {
Field_ID: 3,
FieldName_CR: "Phone",
Source_ID: 2,
SourceName_CR: "Care Two"
},
{
Field_ID: 4,
FieldName_CR: "Email",
Source_ID: 2,
SourceName_CR: "Care Two"
}, ];
const namesBySourceID = Object.fromEntries(
body.map(obj => [obj.Source_ID, obj.SourceName_CR])
);
const result = Object.entries(namesBySourceID)
.map(([Source_ID, SourceName_CR]) => ({ Source_ID, SourceName_CR }));
console.log(result);

关于javascript - 如何在 JavaScript 中使用 id 查找唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73817352/

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