How to change object values with another object key path? - javascript

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

Related

updating/changing values in a nested array in Javascript ES9

The array
let data = [{
"Name": "bob",
"_assets": [{
"income": "100,000",
"Car": {
"Name": "Honda",
"Color": "White"
},
"Boat": {
"Name": "Bertram ",
"Color": "White"
}
}]
}];
The output i'm trying to get is this
[{
" Name": "bob",
"_assets": [{
"income": "100,000",
"Car": "Honda",
"Boat": "Bertram"
}]
}];
Now I've been able to change the nested data, but in the process I lose the outer array. I've done plenty of googling, played around with different answers. Now I'm just burnt on something that seems so easy, but for some reason I'm just completely missing it.
Edit what I'm currently getting
[{
"income": "100,000",
"Car": "Honda",
"Boat": "Bertram"
}]
You need to use nested map:
let data = [{
"Name": "bob",
"_assets": [{
"income": "100,000",
"Car": {
"Name": "Honda",
"Color": "White"
},
"Boat": {
"Name": "Bertram ",
"Color": "White"
}
}]
}];
data = data.map(t => {
return {
"Name": t.Name, "_assets": t._assets.map(x => {
return {
"income": x.income, "Car": x.Car.Name, "Boat": x.Boat.Name
}
})
}
})
console.log(data);

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))

How can I merge duplicate keys in a JavaScript object?

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)

Nested Array in JSON Objects Conversion

I'm struggling with converting the nested JSON array that I have.
{
"Id": "1234",
"Company": {
"element": [{
"Name": "htc",
"Contacts": {
"element": [{
"name": "john",
"phone": "1234"
}, {
"name": "peter",
"phone": "5678"
}]
},
"Address": {
"element": {
"country": "us",
"state": "cali"
}
}
}, {
"Name": "samsung",
"Contacts": {
"element": [{
"name": "luke",
"phone": "0011"
}, {
"name": "james",
"phone": "2233"
}]
},
"Address": {
"element": {
"country": "us",
"state": "texas"
}
}
}]
}
}
As you'll notice, there's this "element" in the arrays "Company", "Contacts" and "Address". But the output that I need to provide should not contain the "element" such as this code:
{
"Id": "1234",
"Company": [{
"Name": "htc",
"Contacts": [{
"name": "john",
"phone": "1234"
}, {
"name": "peter",
"phone": "5678"
}],
"Address": [{
"country": "us",
"state": "cali"
}]
}, {
"Name": "samsung",
"Contacts": [{
"name": "luke",
"phone": "0011"
}, {
"name": "james",
"phone": "2233"
}],
"Address": [{
"country": "us",
"state": "texas"
}]
}]
}
I have no clue how to do in JavaScript. Any ideas/tips are appreciate.
Thank you
You can try something like this:
var data={Id:"1234",Company:{element:[{Name:"htc",Contacts:{element:[{name:"john",phone:"1234"},{name:"peter",phone:"5678"}]},Address:{element:{country:"us",state:"cali"}}},{Name:"samsung",Contacts:{element:[{name:"luke",phone:"0011"},{name:"james",phone:"2233"}]},Address:{element:{country:"us",state:"texas"}}}]}};
var keysToClean = ["Address", "Contacts"]
// Copy object instead of reference
var result = Object.assign({}, data);
result.Company = result.Company.element;
result.Company.forEach(x => {
keysToClean.forEach(k => {
x[k] = Array.isArray(x[k]) ? x[k].element : [x[k].element]
})
})
console.log(result);
Note: I have use Object.create and Arrow functions. They are not supported by old browsers. You can refer to following link for alternative to deep copy an object:
What is the most efficient way to deep clone an object in JavaScript?
The solution using Array.prototype.forEach() function:
var companyData = { "Id": "1234", "Company": { "element": [{ "Name": "htc", "Contacts": { "element": [{ "name": "john", "phone": "1234" }, { "name": "peter", "phone": "5678" }] }, "Address": { "element": { "country": "us", "state": "cali" } } }, { "Name": "samsung", "Contacts": { "element": [{ "name": "luke", "phone": "0011" }, { "name": "james", "phone": "2233" }] }, "Address": { "element": { "country": "us", "state": "texas" } } }] }
};
companyData.Company = companyData.Company.element;
var omitElement = function(o){
if (!o['element']) return o;
return (Array.isArray(o.element))? o.element : [o.element];
}
companyData.Company.forEach(function (o) {
o.Contacts = omitElement(o.Contacts);
o.Address = omitElement(o.Address);
});
console.log(companyData);
Please see this Plunker This should help.. it will generate desired result you need but be aware this is just a way to do this, and only meant for information purpose. It's not production grade...
function ParseData(data)
{
var newObject={Id:0, Company:[]};
newObject["Id"]=data["Id"];
newObject["Company"]=CreateCompanyObject(data["Company"]["element"]);
console.log(JSON.stringify(newObject));
}
function CreateCompanyObject(data)
{
var companies=[];
for(var i=0;i<data.length;i++)
{
companies.push({
name:data[i].Name,
contacts:CreateContactObject(data[i].Contacts.element),
Address:CreateAddressObject(data[i].Address.element)});
};
return companies;
}
function CreateContactObject(data){
var contacts=[];
for(var i=0;i<data.length;i++)
contacts.push(data[i]);
return contacts;
}
function CreateAddressObject(data){
var address=[];
if(typeof(data)=="array"){
for(var i=0;i<data.length;i++)
address.push(data[i]);
}
else
address.push(data);
return address;
}
You could check for element and move the content a step ahead to its parent.
function deleteElement(object){
Object.keys(object).forEach(function (k) {
if (object[k] && typeof object[k] === 'object') {
if ('element' in object[k]) {
object[k] = Array.isArray(object[k].element) ?
object[k].element :
[object[k].element];
}
deleteElement(object[k]);
}
});
}
var data = { Id: "1234", Company: { element: [{ Name: "htc", Contacts: { element: [{ name: "john", phone: "1234" }, { name: "peter", phone: "5678" }] }, Address: { element: { country: "us", state: "cali" } } }, { Name: "samsung", Contacts: { element: [{ name: "luke", phone: "0011" }, { name: "james", phone: "2233" }] }, Address: { element: { country: "us", state: "texas" } } }] } };
deleteElement(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources