I'm trying a different approach to my previous question. Basically, I have a JSON object that looks like this:
var data = {
"tree": {
"id": "99842",
"label": "Bill",
"children": [
{
"id": "27878",
"label": "Tom",
"children": []
}
]
},
"index": {
"27878": {
"birthdate": "1/21/1988",
"spouse": "June",
"hometown": "Tulsa, OK"
},
"99842": {
"birthdate": "4/15/1969",
"spouse": "Mary",
"hometown": "Dallas, TX"
}
}
};
As you can see, there are two "top-level" items: a 'tree' object and an 'index' object. I want to parse them together to get this:
{
"rows": [
{
"id": "99842",
"data": [
{
"birthdate": "4/15/1969",
"spouse": "Mary",
"hometown": "Dallas, TX"
}
],
"rows": [
{
"id": "27878",
"data": [
{
"birthdate": "1/21/1988",
"spouse": "June",
"hometown": "Tulsa, OK"
}
],
"rows": []
}
]
}
]
}
It seems like I could do recursion with Q, but it almost seems like overkill and I have a hard time getting my head wrapped around it. I'm thinking through a solution with callbacks but don't quite have it yet. I'd appreciate any help.
Recursion seems perfectly reasonable. Here's one possible solution:
function nestObjects(tree, index) {
var output;
if (tree && index) {
output = {
id: tree.id,
data: index[tree.id],
rows: []
};
if (Array.isArray(tree.children) && tree.children.length) {
for (var i = 0, len = tree.children.length; i < len; i++) {
output.rows.push(nestObjects(tree.children[i], index));
}
}
}
return output;
}
var result = {
rows: [nestObjects(data.tree, data.index)]
};
console.log(result);
Related
I have an array and it looks as follow:
[
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},.....
]
How do I slice it and get only "companies": and the result as follows:
[
{
"id": 23,
"email": null,
"name": "test"
},.....
]
to clear some issues I have added the function in which I'm using data.map
fn.loadData = function (data) {
var dataKeys = Object.keys(data);
console.log(data)// 'data' is an object
console.log(data.map(x => x.companies)) ///data.map not a function error
var infiniteList = document.getElementById('infinite-list');
infiniteList.delegate = {
createItemContent: function (i) {
return ons._util.createElement(
'<ons-list-item modifier="chevron" tappable>' + data[dataKeys[i]].name + '</ons-list-item>'
);
},
countItems: function () {
return Object.keys(data).length;
}
};
infiniteList.refresh();
}
as comments told you to do:
const data = [
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},
{
"DT_RowId": "row_3758",
"companies": {
"id": 24,
"email": null,
"name": "test3"
},
"USERS": {
"UserId": 24
}
},]
console.log(data.map(obj=>obj.companies))
This worked:
const newArray = [];
for (let i = 0; i < companyArray.length; i++) {
newArray.push(companyArray[i].companies);
}
Thanks, everyone
I have been reading some posts which are related to my question, whereas I have not been able to find a proper solution for what I'm trying to do hear.
I have this JSON file that I am obtaining directly from my database via a sql query:
[
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-21",
"price": 14.173041264216105
}
]
},
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
}
]
My objectif is to be able to sort/transform this json object to a new json object which is classified by the scenario, so, something that looks like:
[
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-21",
"price": 14.173041264216105
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
I have been trying some javascript selfmade functions but I have not obtainend the desired result.
This is the last thing I've tried:
let estructura = [];
for (var j =0; j<obj.length; j++){
for (var i=0; i<estructura.length; i++){
if(obj[j]['scenario'] == estructura[i]['scenario']){
estructura[i]['data'].push(obj[j]['data'])
} else {
console.log("no match, we add the scenario to estructura")
estructura.push(
{
scenario:obj[j]['scenario'],
data: []
})
}
}
}
Thank you
You can achieve this easily with built-in functions like reduce. Iterate over the input, grouping into an object indexed by scenario, creating a object with a data array if the scenario doesn't exist yet, and push to that array:
const input=[{"scenario":"scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18","data":[{"date":"2018-05-21","price":14.173041264216105}]},{"scenario":"scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99","data":[{"date":"2018-05-22","price":42.94691197077433}]}]
console.log(
Object.values(input.reduce((a, { scenario, data }) => {
if (!a[scenario]) a[scenario] = { scenario, data: [] };
a[scenario].data.push(data[0]);
return a;
}, {}))
);
Is there a way/function(s) in lodash to get the object's parent of a particular pet id without having to write code that would loop over each person/pet?
For example: _.getParent(people, pets.id => 11) // returns {"type":"Fish", "id":11}.
let people = [
{
"name": "Jack",
"pets": [
{ "type":"Frog", "id":23 },
{ "type":"Bird", "id":57 },
{ "type":"Fish", "id":11 }
]
},
{
"name": "Dawn",
"pets": [
{ "type":"Lion", "id":89 },
{ "type":"Duck", "id":51 }
]
},
{
"name": "Anne"
},
{
"name": "Josh",
"pets": []
}
]
For example,
_.filter(
_.flatMap(people, 'pets'),
t => t && t.id === 11
)
I'm trying to assign prices to my items from a JSON A to JSON B, managed to get the prices and reassign it to the property but not to the whole object.
here's a snippet of my code, which gets the prices from the first Object and reassigning it to TotalOrignialValue however how can I push it back to the newJson object?
Is there a more pleasing way of achieving this?
// Code goes here
var items = {
"TransactionLine": [
{
"Product": {
"Id": null,
"Codes": [
"1112"
],
"Sku": null
},
"TotalValue": 2.35,
},
{
"Product": {
"Id": null,
"Codes": [
"1113"
],
"Sku": null
},
"TotalValue": 2.15,
}
],
"CustomData": {}
};
var itemPrice = [];
for (var i = 0; i < items.TransactionLine.length; i++) {
var el = items.TransactionLine[i];
itemPrice.push(el.TotalValue);
console.log(el.TotalValue);
}
var newJson = {
"OrderLines": [
{
"Product": {
"Id": 9,
"Codes": [
"1113"
],
"Sku": "CS1113"
},
"TotalOriginalValue": 0, // asign the price here
},
{
"Product": {
"Id": 21,
"Codes": [
"1112"
],
"Sku": "CS1112"
},
"TotalOriginalValue": 0, // asign the price here
}
]
};
var newPrice = [];
for (var x = 0; x < newJson.OrderLines.length; x++) {
var xd = newJson.OrderLines[x].TotalOriginalValue;
xd = itemPrice[x];
newjson = {
"TotalOriginalValue": xd
};
newPrice.push(newjson);
}
console.log('newJSON >> ', newPrice);
Using Lodash makes your life so much easier that does what you need using lodash there is probably an even more succinct way of doing it with it.
var items = {
"TransactionLine": [
{
"Product": {
"Id": null,
"Codes": [
"1112"
],
"Sku": null
},
"TotalValue": 2.35,
},
{
"Product": {
"Id": null,
"Codes": [
"1113"
],
"Sku": null
},
"TotalValue": 2.15,
}
],
"CustomData": {}
};
var newJson = {
"OrderLines": [
{
"Product": {
"Id": 9,
"Codes": [
"1113"
],
"Sku": "CS1113"
},
"TotalOriginalValue": 0, // asign the price here
},
{
"Product": {
"Id": 21,
"Codes": [
"1112"
],
"Sku": "CS1112"
},
"TotalOriginalValue": 0, // asign the price here
}
]
};
var test = _.map(items.TransactionLine, (item,index) => {
return _.set(newJson.OrderLines[index], 'TotalOriginalValue', item.TotalValue)
})
console.log(test)
https://jsfiddle.net/k6vdyhx7/124/
Iterate over OrderLines key value, which is an array, then replace every TotalOriginalValue value with responding value from the items.TransactionLine array.
var items = {TransactionLine:[{Product:{Id:null,Codes:["1112"],Sku:null},TotalValue:2.35},{Product:{Id:null,Codes:["1113"],Sku:null},TotalValue:2.15}],CustomData:{}},
newJson = {OrderLines:[{Product:{Id:9,Codes:["1113"],Sku:"CS1113"},TotalOriginalValue:0},{Product:{Id:21,Codes:["1112"],Sku:"CS1112"},TotalOriginalValue:0}]};
newJson.OrderLines.forEach((v,i) => v.TotalOriginalValue = items.TransactionLine[i].TotalValue);
console.log(newJson);
it looks like your only connection from JSON A to JSON B is the codes array on the items.
You could loop over entries in JSON a, find the corresponding item in JSON B by checking the codes values, and assign the values directly on JSON B entries
var items = {
"TransactionLine": [
{
"Product": {
"Id": null,
"Codes": [
"1112"
],
"Sku": null
},
"TotalValue": 2.35,
},
{
"Product": {
"Id": null,
"Codes": [
"1113"
],
"Sku": null
},
"TotalValue": 2.15,
}
],
"CustomData": {}
};
var newJson = {
"OrderLines": [
{
"Product": {
"Id": 9,
"Codes": [
"1113"
],
"Sku": "CS1113"
},
"TotalOriginalValue": 0, // asign the price here
},
{
"Product": {
"Id": 21,
"Codes": [
"1112"
],
"Sku": "CS1112"
},
"TotalOriginalValue": 0, // asign the price here
}
]
};
items.TransactionLine.forEach(item=>{
var match = newJson.OrderLines.find(entry=>entry.Product.Codes[0] === item.Product.Codes[0]);
if (!match) {
return;
}
match.TotalOriginalValue = item.TotalValue;
});
console.log(newJson);
This will also cut out the use of the array and a loop through the items JSON.
On a list of 2 its not so bad, but add a few hundred/thousand and it will become noticeable.
Here is the my first JSON Array format...
[
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
]
and here is another JSON Array Format
[
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
]
The above mentioned Two JSON Arrays, i need to compare each one with Id and need to format a new JSON Array with caption and value using javascript.
[
[
{
"caption" : "caption1",
"value":"value11"
},
{
"caption" : "caption2",
"value":"value12"
},
{
"caption" : "caption3",
"value":"value13"
}
],
[
{
"caption" : "caption1",
"value":"value21"
},
{
"caption" : "caption2",
"value":"value22"
},
{
"caption" : "caption3",
"value":"value23"
}
]
]
Please help me out.
You can do it in many ways. Below I show two variants:
Option 1: Pure JavaScript
In this example the program preindex first array for faster access to it data, and then loops over second array with map() function to create new array of arrays:
// Create index version of first array
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
// Loop over array of arrays
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
}
});
Option 2: Using special SQL library (Alasql)
Here, you can JOIN to arrays automatically with special SQL statement:
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] \
FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
You can try these variants in working snippet below or play with it in jsFiddle.
(Disclaimer: I am the author of Alasql)
var arr1 = [
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
];
var arr2 = [
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
];
// JavaScript version
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
});
});
document.getElementById("res1").textContent = JSON.stringify(res1);
// Alasql version
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
document.getElementById("res2").textContent = JSON.stringify(res2);
<script src="http://alasql.org/console/alasql.min.js"></script>
<p>Varian 1: JavaScript</p>
<div id="res1"></div>
<p>Variant 2: Alasql</p>
<div id="res2"></div>