[英]javascript extract same values of keys from array of objects
I have hundreds of objects inside each other and under each object there is a repeated object structure with an object inside that contains hundred of keys that are the same and in most of the keys the values are the same also. 我彼此之间有数百个对象,并且每个对象下面都有一个重复的对象结构,其中的对象包含数百个相同的键,并且在大多数键中,值也相同。
What I would like to do is to get from this repeated object the key and value only if its the same across all over the objects and put it aside in an new object that contains all the same repeated pairs of key/value while also remove it from that repeated object inside of every one of the objects. 我想做的就是仅在所有对象中都具有相同的键和值的情况下,才从该重复的对象中获取键和值,并将其放在包含所有相同的重复键/值对的新对象中,同时将其删除从每个对象中重复的对象中提取。
json objects for example: json对象,例如:
[{
"name": "A",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": []
},
{
"name": "A",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": [{
"name": "B",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": [{
"name": "C",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": []
},
{
"name": "C",
"values": {
"ab": "def",
"ac": "1",
"ad": "none"
},
"childs": []
}
]
}]
},
{
"name": "A",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": [{
"name": "D",
"values": {
"ab": "abc",
"ac": "1",
"ad": "none"
},
"childs": []
}]
}]
desired output: 所需的输出:
[{
"name": "A",
"values": {
"ab": "abc"
},
"childs": []
},
{
"name": "A",
"values": {
"ab": "abc"
},
"childs": [{
"name": "B",
"values": {
"ab": "abc"
},
"childs": [{
"name": "C",
"values": {
"ab": "abc"
},
"childs": []
},
{
"name": "C",
"values": {
"ab": "def"
},
"childs": []
}
]
}]
},
{
"name": "A",
"values": {
"ab": "abc"
},
"childs": [{
"name": "D",
"values": {
"ab": "abc"
},
"childs": []
}]
}]
and a new object contains the key/value pairs that were removed because they are the same: 一个新对象包含因相同而被删除的键/值对:
[{
"ac": "1",
"ad": "none"
}]
We could take the first object as a starting point for key value pairs: 我们可以将第一个对象作为键值对的起点:
let pairs = Object.entries( objects[0].values );
Then for all the values we remove non dupes: 然后,对于所有值,我们删除非重复项:
function remove(obj){
pairs = pairs.filter(([key,value]) => obj.values[key] === value);
//the same for all childs:
if(obj.childs) obj.childs.forEach(remove);
}
objects.forEach(remove);
So now weve got a list of key values every object shares, so now we can build an object again: 因此,现在我们获得了每个对象共享的键值列表,因此现在我们可以再次构建对象:
const result = {};
for(let [key,value] of pairs) result[key] = value;
And we can remove duplicates: 我们可以删除重复项:
function dupes(obj){
pairs.forEach(([key]) => {
if( key in obj.values) delete obj.values[key];
});
if(obj.childs) obj.childs.forEach(dupes);
}
objects.forEach(dupes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.