gpt4 book ai didi

javascript - 按值排列的对象紧凑数组(Jquery 或 Underscore)

转载 作者:行者123 更新时间:2023-11-28 11:01:06 27 4
gpt4 key购买 nike

我有一个对象数组:

"Entries" : [ {
"FieldName" : "Name1",
"FieldValue" : "N1Value1"
}, {
"FieldName" : "Name1",
"FieldValue" : "N1Value2"
}, {
"FieldName" : "Name1",
"FieldValue" : "N1Value3"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value1"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value2"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value3"
}, {
"FieldName" : "Name3",
"FieldValue" : "N3Value1"
}, {
"FieldName" : "Name4",
"FieldValue" : "N4Value1"
}, {
"FieldName" : "Name5",
"FieldValue" : "N5Value1"
} ]

我想把它改成:

"Entries" : [ {
"FieldName" : "Name1",
"FieldValue" : ["N1Value1","N1Value2","N1Value3"]
}, {
"FieldName" : "Name2",
"FieldValue" : ["N2Value1", "N2Value2", "N2Value3"]
}, {
"FieldName" : "Name3",
"FieldValue" : "N3Value1"
}, {
"FieldName" : "Name4",
"FieldValue" : "N4Value1"
}, {
"FieldName" : "Name5",
"FieldValue" : "N5Value1"
} ]

我尝试首先在数组中拥有唯一的 FieldName 值,然后在 JSON 数组中使用 _.filter 来尝试接收数组作为返回,但我得到的只是整个对象。

    $.each(arrUniqueFieldNames, function() {
var strFName = String(this);
oEntries[this] = _.filter(jsonEntries, function (item) {
if (item.FieldName === strFName) {
return String(item.FieldValue)
}
});
});

这段代码中可能有一些缺陷,但它并没有像我预期的那样工作,因为它返回整个对象而不仅仅是值。

我还尝试用 _.map 替换 _.filter,但结果是我得到的每个数组都有很多“未定义”。

最佳答案

我知道你想用 jquery 来实现,但我对此不太坚定,所以我给你一个纯 JavaScript 的解决方案:

test =  [ {
"FieldName" : "Name1",
"FieldValue" : "N1Value1"
}, {
"FieldName" : "Name1",
"FieldValue" : "N1Value2"
}, {
"FieldName" : "Name1",
"FieldValue" : "N1Value3"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value1"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value2"
}, {
"FieldName" : "Name2",
"FieldValue" : "N2Value3"
}, {
"FieldName" : "Name3",
"FieldValue" : "N3Value1"
}, {
"FieldName" : "Name4",
"FieldValue" : "N4Value1"
}, {
"FieldName" : "Name5",
"FieldValue" : "N5Value1"
} ];

result =[];

for (i=0; i<test.length; i++)
{
element=test[i];
key=element['FieldName'];
value=element['FieldValue'];
if (!(key in result))
result[key] = [value];
else
result[key].push(value);
}
console.log(result);

关于javascript - 按值排列的对象紧凑数组(Jquery 或 Underscore),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190019/

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