gpt4 book ai didi

javascript - 合并对象数组中的重复对象

转载 作者:可可西里 更新时间:2023-11-01 01:18:17 25 4
gpt4 key购买 nike

我有以下对象数组,

var data = [
{
label: "Book1",
data: "US edition"
},
{
label: "Book1",
data: "UK edition"
},
{
label: "Book2",
data: "CAN edition"
}
];

我想根据属性“标签”合并重复的对象这样最终输出将如下所示,

var data = [
{
label: "Book1",
data: ["US edition", "UK edition"] //data attribute is merged
},
{
label: "Book2",
data: "CAN edition"
}
];

有人可以帮我确定方法吗?

最佳答案

我可能会使用 filter 进行循环,跟踪我之前见过的对象 map ,沿着这些线(编辑以反射(reflect)您同意是的,它是有意义的使 (entry).data 总是一个数组):

var seen = {};
data = data.filter(function(entry) {
var previous;

// Have we seen this label before?
if (seen.hasOwnProperty(entry.label)) {
// Yes, grab it and add this data to it
previous = seen[entry.label];
previous.data.push(entry.data);

// Don't keep this entry, we've merged it into the previous one
return false;
}

// entry.data probably isn't an array; make it one for consistency
if (!Array.isArray(entry.data)) {
entry.data = [entry.data];
}

// Remember that we've seen it
seen[entry.label] = entry;

// Keep this one, we'll merge any others that match into it
return true;
});

在 ES6 环境中,我会使用 seen = new Map() 而不是 seen = {}

注意:Array.isArray 是由 ES5 定义的,因此一些较旧的浏览器(如 IE8)不会包含它。不过,它可以很容易地填充/填充:

if (!Array.isArray) {
Array.isArray = (function() {
var toString = Object.prototype.toString;
return function(a) {
return toString.call(a) === "[object Array]";
};
})();
}

旁注:我可能还会总是entry.data 设为一个数组,即使我没有看到它的两个值,因为一致数据结构更容易处理。我没有在上面那样做,因为当只有一个匹配的条目时,你的最终结果显示 data 只是一个字符串。 (我们现在已经在上面做了。)

实例(ES5 版本):

var data = [
{
label: "Book1",
data: "US edition"
},
{
label: "Book1",
data: "UK edition"
},
{
label: "Book2",
data: "CAN edition"
}
];
snippet.log("Before:");
snippet.log(JSON.stringify(data, null, 2), "pre");
var seen = {};
data = data.filter(function(entry) {
var previous;

// Have we seen this label before?
if (seen.hasOwnProperty(entry.label)) {
// Yes, grab it and add this data to it
previous = seen[entry.label];
previous.data.push(entry.data);

// Don't keep this entry, we've merged it into the previous one
return false;
}

// entry.data probably isn't an array; make it one for consistency
if (!Array.isArray(entry.data)) {
entry.data = [entry.data];
}

// Remember that we've seen it
seen[entry.label] = entry;

// Keep this one, we'll merge any others that match into it
return true;
});
snippet.log("After:");
snippet.log(JSON.stringify(data, null, 2), "pre");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - 合并对象数组中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025965/

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