I have an API response in form of JSON.
"reports": [
{
"columnHeader": {
"dimensions": [
"ga:date"
],
"metricHeader": {
"metricHeaderEntries": [
{
"name": "ga:sessions",
"type": "INTEGER"
},
{
"name": "ga:users",
"type": "INTEGER"
}
]
}
},
"data": {
"rows": [
{
"dimensions": [
"20210623"
],
"metrics": [
{
"values": [
"13",
"13"
]
}
]
},
{
"dimensions": [
"20210624"
],
"metrics": [
{
"values": [
"18",
"16"
]
}
]
}
]}}]}
I need to get each metric (metricHeaderEntries) with its values in a separate Object, which is therefore is in an array "dataTracesAll".
//Example of the construction
//dataTracesAll is an array, containing objects with key "trace" + int
dataTracesAll['trace' + (i+1)] = {
name: metricsTitles[i].name, //metric title "sessions"
x: dimensions, //list of dimensions ["20210623", "20210624"]
y: dataClear //list of metrics for each metrics is separate ["13", "18"]
}
//The full code:
var titles = [];
var dataTracesAll = [];
//raw data
for (var i=0; i < data.reports.length; i++) {
//get titles
var metricsTitles = data.reports[i].columnHeader.metricHeader.metricHeaderEntries;
metricsTitles.forEach(function(title) {
titles.push(title.name.split("ga:")[1]);
});
//values and dates raw
var dimensions = [];
var dataClear = [];
var values = data.reports[i].data.rows;
//get dates and values
values.forEach(function(val) {
dimensions.push(val.dimensions[0]);
dataClear.push(val.metrics[0].values[0]); //only the first array value is added
});
//clear values
console.log(values);
//constuct array with values
dataTracesAll['trace' + (i+1)] = {
name: metricsTitles[i].name,
x: dimensions,
y: dataClear
}
}
Result of the code:
The problem is that it adds only the first value of the metrics value array and I cannot get how to parse everything, so there is actually 2 traces.
My ideal result is:
dataTracesAll = [
trace1: {
name: "ga:sessions",
x: ['20210623', '20210624']
y: ['13', '18']
},
trace2: {
name: "ga:users",
x: ['20210623', '20210624']
y: ['13', '16']
}
];
Try this:
var data = {"reports": [
{
"columnHeader": {
"dimensions": [
"ga:date"
],
"metricHeader": {
"metricHeaderEntries": [
{
"name": "ga:sessions",
"type": "INTEGER"
},
{
"name": "ga:users",
"type": "INTEGER"
}
]
}
},
"data": {
"rows": [
{
"dimensions": [
"20210623"
],
"metrics": [
{
"values": [
"13",
"13"
]
}
]
},
{
"dimensions": [
"20210624"
],
"metrics": [
{
"values": [
"18",
"16"
]
}
]
}
]}}]};
var titles = [];
var dataTracesAll = [];
var length = data.reports[0].data.rows[0].metrics[0].values.length;
//raw data
for (var i=0; i < length; i++) {
//get titles
var metricsTitles = data.reports[0].columnHeader.metricHeader.metricHeaderEntries;
metricsTitles.forEach(function(title) {
titles.push(title.name.split("ga:")[1]);
});
//values and dates raw
var dimensions = [];
var dataClear = [];
var values = data.reports[0].data.rows;
//get dates and values
values.forEach(function(val) {
dimensions.push(val.dimensions[0]);
dataClear.push(val.metrics[0].values[i]);
});
//constuct array with values
dataTracesAll.push({});
dataTracesAll[i]['trace' + (i+1)] = {
name: metricsTitles[i].name,
x: dimensions,
y: dataClear
}
}
console.log(dataTracesAll);
Edit: The result was supposed to be an array, so I changed the code accordingly.
I have updated you logic to make it fit for your requirement. Hope this will work.
const data =
{
"reports": [
{
"columnHeader": {
"dimensions": [
"ga:date"
],
"metricHeader": {
"metricHeaderEntries": [
{
"name": "ga:sessions",
"type": "INTEGER"
},
{
"name": "ga:users",
"type": "INTEGER"
}
]
}
},
"data": {
"rows": [
{
"dimensions": [
"20210623"
],
"metrics": [
{
"values": [
"13",
"13"
]
}
]
},
{
"dimensions": [
"20210624"
],
"metrics": [
{
"values": [
"18",
"16"
]
}
]
}
]
}
}]
}
const dataTracesAll = {};
const report = data.reports[0];
for (var i = 0; i < report.data.rows.length; i++) {
dataTracesAll[`trace${i + 1}`] = {
name: report.columnHeader.metricHeader.metricHeaderEntries[i].name,
x: [],
y: [],
}
}
Object.keys(dataTracesAll).forEach((key, index) => {
for (var i = 0; i < report.data.rows.length; i++) {
dataTracesAll[key].x.push(report.data.rows[i].dimensions[0]);
dataTracesAll[key].y.push(report.data.rows[i].metrics[0].values[index]);
}
})
console.log(dataTracesAll);
Related
What I want is to find an object in a nested array, and to get it by a pre-known ScheduleId number, and where the Duration property is defined.
We need to find this element which is contained inside of array of "Columns", and "Columns" are contained within "Table" elements.
After finding this object, I want to update ScheduleId = 0 and Duration = 0.
Sample data:
var data = {
"Headers": [
"A",
"B",
"C",
"D"
],
"Table": [
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 12,
},
],
},
{
"Columns": [
{
"Duration": 22,
"ScheduleId": 44,
},
],
},
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 1648,
},
],
},
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 22,
},
],
},
]
};
Pseudo code:
var requestedScheduleId = 22;
var requestedObj = data.Table.find(x => requestedScheduleId.Equals(x.Columns.ScheduleId) )
requestedObj.ScheduleId = 0;
requestedScheduleId.Duration = 0;
Unsuccessful attempt:
var test = data.Table.map(({ Columns }) => {return Columns = Columns.filter(({ ScheduleId }) => ScheduleId == 22 )});
console.log(test);
I would not use .map or .filter for this. It's a plain and simple nested loop: For each table, for each column, if condition is met, do something.
Either with for loops:
for (table of data.Table) {
for (column of table.Columns) {
if (column.ScheduleId === 22) {
column.ScheduleId = 0;
column.Duration = 0;
}
}
}
or with Array#forEach:
data.Table.forEach(table => {
table.Columns.forEach(column => {
if (column.ScheduleId === 22) {
column.ScheduleId = 0;
column.Duration = 0;
}
});
});
var data = {
"Headers": [
"A",
"B",
"C",
"D"
],
"Table": [
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 12,
},
],
},
{
"Columns": [
{
"Duration": 22,
"ScheduleId": 44,
},
],
},
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 1648,
},
],
},
{
"Columns": [
{
"Duration": 0,
"ScheduleId": 22,
},
],
},
]
};
var requestedScheduleId = 22;
data.Table.forEach(table => {
table.Columns.forEach(column => {
if (column.ScheduleId === requestedScheduleId) {
column.ScheduleId = 0;
column.Duration = 0;
}
});
});
console.log(data);
I need your help for create a tree like data structure with given JSON as shown below and required output structure already given below. I am a beginner in programming and I have only a little knowledge in data structure
JSON from API
[
"",
[
"Test",
[
"Test/sample",
[
"Test/sample/sample1"
]
],
[
"Test/test3"
]
],
[
"Test1",
[
"Test1/test2"
]
],
[
"cat"
]
]
Output like below structure
{
"key": "Image",
"label": "Image",
"icon": 'pi pi-folder',
"children": []
},
{
"key": "Test",
"label": "Test",
"icon": "pi pi-folder",
"children": [
{
"key": "Test/sample",
"label": "Sample",
"icon": "pi pi-folder",
"children": [{
"key": "Test/sample/sample1",
"label": "Sample1",
"icon": 'pi pi-folder',
"children": []
}]
},
{
"key": "Test/test3",
"label": "test3",
"icon": "pi pi-folder",
"children": []
},
]
},
{
"key": "Test1",
"label": "Test1",
"icon": "pi pi-folder",
"children": [{
"key": "Test1/test2",
"label": "test2",
"icon": "pi pi-folder",
"children": []
}]
},
{
"key": "cat",
"label": "cat",
"icon": "pi pi-folder",
"children": []
},
]
Above structure is image file directory and directory name is indicated by label and icon is indicating directory, children show sub directory
Console value of API
It can easily archive with recursive function
const icon = "pi pi-folder";
var a = [
"",
[
"Test",
[
"Test/sample",
[
"Test/sample/sample1"
]
],
[
"Test/test3"
]
],
[
"Test1",
[
"Test1/test2"
]
],
[
"cat"
]
]
/**
* #param {Array} arr The child array
*/
function createChildNode(arr) {
let key = "Image";
let label = "Image";
let children = [];
if (arr.length >= 1) {
key = arr[0];
label = key.includes("/") ? key.split("/").pop() : key;
label = label.charAt(0).toUpperCase() + label.slice(1);
for (let index = 1; index < arr.length; index++) {
const element = arr[index];
children.push(createChildNode(element));
}
}
return {key: key, label: label, icon: icon, children: children};
}
var b = []
for (let index = 0; index < a.length; index++) {
const element = a[index];
b.push(createChildNode(element));
}
console.log(b);
This is what I have: I want to merge object which key begins with "path-"+i . And to strip "path-i" from keys in end result.
var arr = [
{
"key": "path-0-mp4",
"value": [
"media/video/01.mp4",
"media/video/01_hd.mp4"
]
},
{
"key": "path-0-quality",
"value": [
"720p",
"1080p"
]
},
{
"key": "path-1-mp4",
"value": [
"media/video/02.mp4",
"media/video/02_hd.mp4"
]
},
{
"key": "path-1-quality",
"value": [
"SD",
"HD"
]
}
]
This is a desired result:
var arr = [
[
{
"mp4": "media/video/01.mp4",
"quality": "720p"
},
{
"mp4": "media/video/01_hd.mp4",
"quality": "1080p"
},
],
[
{
"mp4": "media/video/02.mp4",
"quality": "SD"
},
{
"mp4": "media/video/02_hd.mp4",
"quality": "HD"
},
],
]
I started doing something but its not even close:
var key, new_key, value,j=0, z=0, parr = [], obj;
for(var i = 0;i<a.length;i++){
console.log('item:' ,a[i])
key = a[i].key, value = a[i].value
if(key.indexOf('path-'+j.toString()) > -1){
new_key = key.substr(key.lastIndexOf('-')+1)
console.log(key, new_key, value)
for(var z = 0;z<value.length;z++){
parr.push({[new_key]: value[z] })
}
}
}
console.log(parr)
[
{
"mp4": "media/video/01.mp4"
},
{
"mp4": "media/video/01_hd.mp4"
},
{
"quality": "720p"
},
{
"quality": "1080p"
}
]
edit:
Array could petencially hols different keys that would need grouping in the same way, for example:
var arr = [
{
"key": "path-0-mp4",
"value": [
"media/video/01.mp4",
"media/video/01_hd.mp4"
]
},
{
"key": "path-0-quality",
"value": [
"720p",
"1080p"
]
},
{
"key": "path-1-mp4",
"value": [
"media/video/02.mp4",
"media/video/02_hd.mp4"
]
},
{
"key": "path-1-quality",
"value": [
"SD",
"HD"
]
},
{
"key": "subtitle-0-label",
"value": [
"English",
"German",
"Spanish"
]
},
{
"key": "subtitle-0-src",
"value": [
"data/subtitles/sintel-en.vtt",
"data/subtitles/sintel-de.vtt",
"data/subtitles/sintel-es.vtt"
]
},
{
"key": "subtitle-1-label",
"value": [
"German",
"Spanish"
]
},
{
"key": "subtitle-1-src",
"value": [
"data/subtitles/tumblr-de.vtt",
"data/subtitles/tumblr-es.vtt"
]
}
]
This is a desired result (create new array for each different key):
var arr = [
[
{
"mp4": "media/video/01.mp4",
"quality": "720p"
},
{
"mp4": "media/video/01_hd.mp4",
"quality": "1080p"
},
],
[
{
"mp4": "media/video/02.mp4",
"quality": "SD"
},
{
"mp4": "media/video/02_hd.mp4",
"quality": "HD"
},
],
],
arr2 = [
[
{
"label": "English",
"src": "data/subtitles/sintel-en.vtt",
},
{
"label": "German",
"src": "data/subtitles/sintel-de.vtt"
},
{
"label": "Spanish",
"src": "data/subtitles/sintel-es.vtt"
}
],
[
{
"label": "Spanish",
"src": "data/subtitles/tumblr-es.vtt",
},
{
"label": "German",
"src": "data/subtitles/tumblr-de.vtt"
}
]
]
You could split the key property, omit the first path and take the rest as index and key. Then create a new array, if not exists and assign the values.
var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }],
result = data.reduce((r, { key, value }) => {
let [, i, k] = key.split('-');
r[i] = r[i] || [];
value.forEach((v, j) => (r[i][j] = r[i][j] || {})[k] = v);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you like to group by the first part of key, you could take an object with this group as key and assign the rest as above.
var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }, { key: "subtitle-0-label", value: ["English", "German", "Spanish"] }, { key: "subtitle-0-src", value: ["data/subtitles/sintel-en.vtt", "data/subtitles/sintel-de.vtt", "data/subtitles/sintel-es.vtt"] }, { key: "subtitle-1-label", value: ["German", "Spanish"] }, { key: "subtitle-1-src", value: ["data/subtitles/tumblr-de.vtt", "data/subtitles/tumblr-es.vtt"] }],
result = data.reduce((r, { key, value }) => {
let [group, i, k] = key.split('-');
if (!r[group]) r[group] = [];
if (!r[group][i]) r[group][i] = [];
value.forEach((v, j) => {
if (!r[group][i][j]) r[group][i][j] = {};
r[group][i][j][k] = v;
});
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am new to this and a beginner,
is this the correct approach?
const a = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];
var resp = [];
for (let i = 0; i < a.length; i++) {
var inst = a[i];
var key = inst["key"];
for (let j = 0; j < inst.value.length; j++) {
var index = key.split("-")[1];
var keyinst = key.split("-")[2];
if (!resp[index]) {
resp[index] = [];
}
if (!resp[index][j]) {
resp[index][j] = {};
}
resp[index][j][keyinst] = inst.value[j];
}
}
console.log(resp);
I find this easier to read and grasp
You can save an assignment if you use reduce
const arr = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];
newArr = [];
arr.filter(item => item.key.endsWith("mp4"))
.forEach(item => item.value
.forEach((val, i) => newArr.push({
"mp4": val,
"quality": arr.find(qItem => qItem.key === item.key.replace("mp4", "quality")).value[i]}
)
)
)
console.log(newArr)
Here is Nina's version in an unobfuscated version
var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }],
result = data.reduce((resultArray, { key, value }) => {
let [, idx, suffix] = key.split('-');
resultArray[idx] = resultArray[idx] || [];
value.forEach((val, i) => (resultArray[idx][i] = resultArray[idx][i] || {})[suffix] = val);
return resultArray;
}, []);
console.log(result);
The only odd thing I did here was using an object as a lookup table to help with the speed complexity. If you have any questions let me know.
const arr = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];
const result = arr.reduce((table, item) => {
// Getting "path-1" from "path-1-quality"
const pathValues = item.key.split('-');
const pathValue = pathValues[0] + '-' + pathValues[1];
// Getting "quality" from "path-1-quality"
const key = pathValues[2];
// Get Index from table if already registered paths
let tIndex = table.indexLookup[pathValue];
// If there is no registered index register one
if (tIndex === undefined) {
// reassign index to new location
tIndex = table.result.length;
// register the index
table.indexLookup[pathValue] = tIndex;
table.result.push([]);
}
// Assign values
item.value.forEach((value, i) => {
const arr = table.result[tIndex] || [];
arr[i] = arr[i] || {}
arr[i][key] = value;
table.result[tIndex] = arr;
})
return table
}, {
indexLookup : {},
result: []
}).result
console.log(result)
I have an array of data that looks like this:
{
"data": [
{
"id": "20200722_3",
"eventDate": "2020-07-22T00:00:00",
"eventName": "Football",
"eventDetails": [
"Men's First Round (2 matches)"
],
"eventVenue": "Venue A"
},
{
"id": "20200722_1",
"eventDate": "2020-07-22T00:00:00",
"eventName": "Football",
"eventDetails": [
"Men's First Round (2 matches)"
],
"eventVenue": "Venue B"
}
]
}
Now I wanted to group the data by multiple properties. For example, by eventDate, eventName, eventDetails, and eventVenue. Which I've done with this code referenced from this post:
const groupBy = (array, attrs) => {
var output = [];
for (var i = 0; i < array.length; ++i) {
var ele = array[i];
var groups = output;
for (var j = 0; j < attrs.length; ++j) {
var attr = attrs[j];
var value = ele[attr];
var gs = groups.filter(g => {
return g.hasOwnProperty('label') && g['label'] === value;
});
if (gs.length === 0) {
var g = {};
if (isArray.g['label'] ) {
}
g['label'] = value;
g['groups'] = [];
groups.push(g);
groups = g['groups'];
} else {
groups = gs[0]['groups'];
}
}
groups.push(ele);
}
return output;
}
var result = groupBy(data, ['eventDate', 'eventName', 'eventDetails', 'eventVenue'])
Which results in an array like this:
[{
"label": "2020-07-23T00:00:00",
"groups": [{
"label": "Football",
"groups": [{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue A",
"groups": [
"Object"
]
}]
},
{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue B",
"groups": [
"Object"
]
}]
}
}]
}]
}]
You can see that for the output above, there are two separate "groups" that have the label "Men's First Round (2 matches)". I'm trying to figure out how I can combine these objects that have duplicate value ? I'm looking for something that would output like this:
[{
"label": "2020-07-23T00:00:00",
"groups": [{
"label": "Football",
"groups": [{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue A",
"groups": [
"Object"
]
},
{
"label": "Venue B",
"groups": [
"Object"
]
}]
}]
}]
}]
Any help would be greatly appreciated.
I'll share the answer that I came up with for those that are curious.
For my needs, I know that if the array with the eventName only contained 1 attribute, it could be a duplicate. So in order to fix that, I converted the array that only had 1 value to a string:
if (ele[attr] && ele[attr].length === 1) {
var value = ele[attr].toString();
} else {
var value = ele[attr];
}
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.