How can I merge duplicate keys in a JavaScript object? - javascript

I have a JavaScript object as follows :
{
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
I want to merge duplicate key in "$origin" and append value in "a" key
{
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
},
{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
I know how to merge duplicate keys from two different object from other topics, but I don't know how to merge and find duplicate keys in the same object.

First of all, use reduce to collect the duplicates and save them in a temporary object with values of $origin as its keys. Then iterate the keys and reconstruct the the object.
Another way would be doing most of the work in the reduce method with some filtering but I think my current solution is faster.
const data = {
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
},
{
"$origin": "eomainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
const result = { zone: [] }
const tmp = data.zone.reduce((acc, curr) => {
if (acc.hasOwnProperty(curr.$origin)) {
acc[curr.$origin] = acc[curr.$origin].concat(curr.a)
} else {
acc[curr.$origin] = curr.a
}
return acc;
}, {})
result.zone = Object.keys(tmp).map((key) => {
return {
$origin: key,
a: tmp[key]
}
})
console.log(result)

You can loop through the array starting from index 1 and keep on pushing the values in the object at index 0
let x = {
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
// starting to loop from index 1, new elements will be pushed
to the object at index 0
for (var i = 1; i < x.zone.length; i++) {
// looping through the array of object at index 1 ...
x.zone[i].a.forEach(function(item) {
// dummy object which will have values from other objects
let dumObj = {};
dumObj.name = item.name;
dumObj.ip = item.ip;
x.zone[0].a.push(dumObj);
})
}
console.log(x)

Related

How to convert flat data to hierarchical JSON?

I use a fake api with this json, I still haven't been able to with this function, I need to convert the structure to look like this and I need to convert this data and then unconvert when saving
so that I change the parameters blockId to id, blockParent to parent.
{
"blocks": [
{
"blockId": "12",
"name": "Sierra",
"abrv": "Sir",
"blockParent": "0"
},
{
"blockId": "23",
"name": "Velasco",
"abrv": "Vel",
"blockParent": "12"
},
{
"blockId": "32",
"name": "UnitOne",
"abrv": "Uni",
"blockParent": "23"
},
{
"blockId": "48",
"name": "Vani",
"abrv": "Van",
"blockParent": "12"
},
{
"blockId": "57",
"name": "UnitTwo",
"abrv": "UniTwo",
"blockParent": "48"
}
]
}
const flatToTree = (blocks: IListBlocks[]) => {
const array: IListBlocks[] = []
const children: IListBlocks[] = []
blocks.forEach((block) => {
if (block.blockParent === block.blockId) {
array.push(block)
} else {
children.push(block)
}
})
array.forEach((block) => {
block.children = children.filter(
(child) => child.blockParent === block.blockId,
)
})
return array
}
{
"id": "12",
"title": "Sierra",
"subtitle": "Sir",
"parent": "0",
"children": [
{
"id": "13",
"title": "Sierra",
"subtitle": "Sir",
"parent": "12",
}
]
}

How to change object values with another object key path?

How to change the destination values with source object key path?
The source object is like below
{
"total-info": [{
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "peter",
"income": "$400"
},
{
"name": "peter wife",
"income": "$500"
}
]
}
}
}, {
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "John",
"income": "$900"
},
{
"name": "John wife",
"income": "$400"
}
]
}
}
}]
}
The destination is like this:
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "$3000"
}
}, {
"John": {
"id": "emp02",
"sal": "$5000"
}
}]
}
Then how do I change the destination object to the below format?
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}, {
"John": {
"id": "emp02",
"sal": "['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}]
}
Can you please tell me how transform to arrays like above. Thanks you

Objects keys value to be updated with arrays value

Below is my Attempt, I have an object which has array of objects within it, it has a field: 'positionTitle'.
I also have an array of objects which also has a 'positionTitle'
They both have similar data I want all of the values for the positionTitles in my 'individualsData' to go into 'graphData' and be able to now use this new graphData!
I think my attempt is wrong its treating them both as arrays?
Thanks, Dale
graphData = {
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
}
]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "Adnan A. Khan"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "Christine Leong"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
What I expect to see:
NEWgraphData = {
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy" <== from individualsdata
}
}]
}]
}
]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Managing Director" <== also from individuals data
}
}]
}]
}
graphData.engagementAreas.map((el, i) => {
el.engagementTypes.engagements.members.position.positionTitle = individualsData.positions.positionTitle;
return el;
})
As engagementTypes, engagements and members properties are also array of objects, you have to loop them as well as below.
graphData.engagementAreas.map((el, i) => {
el.engagementTypes.forEach((et) => {
et.engagements.forEach((eg) => {
eg.members.forEach((mem) => {
mem.position.positionTitle = individualsData.positions.positionTitle; // make sure this is correct
});
});
});
return el;
})
Here is the solution. but you have to choose what individual data item will be the pick for the positionTitle
graphData.engagementAreas.map((el, i) => {
return el.engagementTypes.map((el2,i2) => {
return el2.engagements.map( (el3,i3) => {
return el3.members.map((el4,i4) => {
return el4.position.positionTitle =individualsDt[0].positions.[0].positionTitle;// take a look here, i just pick positionTitle staticly
})
})
})
});
see implementation in console here enter link description here

Complex JSON structure with JS

I'm looking for a way to generate an HTML table from a JSON data.
I'm limitated with tooling options because we use CMS, so I can only use JS, JQuery and ApacheVelocity (without making new templates, only using the 'syntax').
Well, I get this kind of JSON data from remote API:
{
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
The first problem I face are those numeric indexes.
The only way to make reference to this is like this:
arr_from_json.data.data.region[123].game[11844220].team1_name
It is ok if we only have a few "games" extracted, even 100 games. But it is impossible to keep it updated with thousands of games who are constantly being updated.
Is there some way for iterarte through this ugly JSON structure?
Many thanks
Edit:
I want to create a table with the distinct games:
Zorya Luhansk - SC Braga
W1 X W2
2.39 3.01 2.82
Most important data/keys to me are: both team names, name of the possible outcome and price.
You can convert those indexed objects into traditional arrays using a helper function, then iterate over the data in a more natural way after transforming it. See below for an example using Array.map and the helper function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
const resp = {
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
function parseGameData(data){
return keysToArray(data.region).map(obj => keysToArray(obj.game).map(obj => {
obj.market = keysToArray(obj.market).map(obj => {
return {
name: obj.name,
event: keysToArray(obj.event)
}
})
return obj
}))
}
console.log(parseGameData(resp.data.data))

remove elements from nested object array

I want to remove object based on conditional check from the JSON object using angularjs/jQuery.
I tried with below code but output is not as expected.
Demo: https://plnkr.co/edit/EWwbETITqn7G79Xypt0g?p=preview
angular.module('ui.bootstrap.demo').controller('DataCtrl', function ($scope) {
$scope.responseData = {
"data": [{
"name": "Machine", "quantity": 20, "snVal": 22,
"machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" },
{ "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }],
"machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" },
{ "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }
]
}]
}
console.log("R1 :: " + JSON.stringify($scope.responseData));
$scope.newResponse = $.grep($scope.responseData.data, function (element, index) { return element.status == "delivered" }, true);
console.log("R2 after removing elements:: " + JSON.stringify($scope.newResponse));
});
Try this,
let responseData = { "data": [{ "name": "Machine", "quantity": 20, "snVal": 22, "machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" }, { "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }], "machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" }, { "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }] }] } ;
let newResponse = responseData;
newResponse.data.forEach(function (item) {
for (j in item) {
if (j.includes("machine")) {
//better you check if type is array, using Object.prototype.toString.call(j) === "[object Array]"
item[j] = item[j].reduce(function (acc, machine) {
if (machine.status !== "delivered"){
acc.push(machine);
}
return acc;
}, []);
}
}
})|
console.log(newResponse);
Here we are just iterating through all objects in the data field. Since properties like machine1, machine2 is an array, we iterate through it and filter all machines which are not delivered.
You must note that I have used a for-in loop and array reduce() method here.

Categories

Resources