Reorder a provided JSON to a Specified Format - javascript

I need an optimized way to reorder the following JSON in JavaScript:
[
{"Values":["2005","Australia","$304749.10"]},
{"Values":["2005","France","$143130.80"]},
{"Values":["2006","Australia","$651979.82"]},
{"Values":["2006","France","$332496.01"]},
]
into this format:
[
{"Values":["Australia","2005","$304749.10"]},
{"Values":["Australia","2006","$651979.82"]},
{"Values":["France","2005","$143130.80"]},
{"Values":["France","2006","$332496.01"]},
]

var data=[
{"Values":["2005","Australia","$304749.10"]},
{"Values":["2005","France","$143130.80"]},
{"Values":["2006","Australia","$651979.82"]},
{"Values":["2006","France","$332496.01"]},
]
May reorder the props first:
data=data.map(({Values:[year,location,price]})=>({Values:[location,year,price}]));
Then sort alphabetically after the first prop:
data.sort(({Values:[loca]},{Values:[locb]})=>loca.localeCompare(locb));
http://jsbin.com/yekiropozu/edit?console
Note that this uses ES6 object destructuring...

You could first swap the first two items of the inner array and then sort the whole array by country and then by year.
var array = [{ Values: ["2005", "Australia", "$304749.10"] }, { Values: ["2005", "France", "$143130.80"] }, { Values: ["2006", "Australia", "$651979.82"] }, { Values: ["2006", "France", "$332496.01"] }];
array.forEach(a => [a.Values[0], a.Values[1]] = [a.Values[1], a.Values[0]]);
array.sort((a, b) => a.Values[0].localeCompare(b.Values[0]) || a.Values[1] - b.Values[1]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

<script>
var data = [
{"Values":["2005","Australia","$304749.10"]},
{"Values":["2005","France","$143130.80"]},
{"Values":["2006","Australia","$651979.82"]},
{"Values":["2006","France","$332496.01"]},
];
var data2 = data;
for(i=0;i<data.length;i++){
data2[i].Values[1] = data[i].Values[0];
data2[i].Values[0] = data[i].Values[1];
}
console.log(data2);
</script>

Related

How to merge objects and append it into new array if object values are same using JavaScript?

I have this kind of data, my goal is to find all same request_id values in the given objects, merge it to one object and append its unique_id into one array, How can I get this result?
let fakeData = {
"622b1e4a8c73d4742a66434e212":{
request_id: "1",
uique_id:'001'
},
"622b1e4a8c73d4742a6643423e54":{
request_id: "1",
uique_id:'002'
},
"622b1e4a8c73d4742a6643423e23":{
request_id: "2",
uique_id:'003'
},
}
let parts = []
for (const property in fakeData) {
console.log(fakeData[property]);
}
//Result should be
// [{request_id:'1', values:["001, 002"]}, {request_id:'2', values:["003"]}]
You can iterate over all the values using Object.values() and array#reduce. In the array#reduce group based on request_id in an object and extract all the values of these object using Object.values().
const fakeData = { "622b1e4a8c73d4742a66434e212": { request_id: "1", uique_id: '001' }, "622b1e4a8c73d4742a6643423e54": { request_id: "1", uique_id: '002' }, "622b1e4a8c73d4742a6643423e23": { request_id: "2", uique_id: '003' }, },
output = Object.values(fakeData).reduce((r, {request_id, uique_id}) => {
r[request_id] ??= {request_id, values: []};
r[request_id].values.push(uique_id);
return r;
},{}),
result = Object.values(output);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add nested json object item to another json item

I want to add two nested objects in JSON in typescript.
In JSON given below I want to add second JSON's activityLogs item in first JSON's activityLogs.
JSON1:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
JSON2:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}]
Result:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"},
{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
How I can do this?
You can use push() with the spread operator or concat and reassign:
var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
JSON1[0].activityLogs.push(...JSON2[0].activityLogs)
console.log(JSON1)
This assumes that your json arrays contain just the one top-level object. If that's not the case you need to add more details about how the two arrays are synchronized (for example will vehicleno be the same in both?).
As an example, if the vehicleno is a unique identifier in both arrays you could create a lookup of the JSON1 values and the use that to push into the appropriate arrays. This will update JSON1 in place even if it contains multiple vehicles:
var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
let lookup = JSON1.reduce((lookup, obj) => {
lookup[obj.vehicleno] = obj
return lookup
}, {})
JSON2.forEach(obj => lookup[obj.vehicleno].activityLogs.push(...obj.activityLogs))
console.log(JSON1)
You can use concatination array method.
let json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}];
let json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
let result = json1[0].activityLogs.concat(json2[0].activityLogs);
console.log(result);
The simplest way is to concat the activityLogs:
var arr1 = [{
"vehicleno": "SV028",
"devicE_CODE": "8505",
"activityLogs": [{
"gpsdate": "01/03/2019",
"gpstime": "13:40:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:38:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:37:18"
}
]
}];
var arr2 = [{
"vehicleno": "SV028",
"devicE_CODE": "8505",
"activityLogs": [{
"gpsdate": "01/03/2019",
"gpstime": "13:46:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:43:18"
}
]
}];
var arr3 = arr1[0].activityLogs.concat(arr2[0].activityLogs);
console.log(arr3);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
Note this will only work if you only have one object in the top-level array.
result = json1;
/// result = Object.assign({}, json1); if you don't want to mutate the original json1
result.forEach(elem1 => elem1.activityLogs
.concat(json2.find(elem2 => elem2.vehicleno === elem1.vehicleno).activityLogs));
Concat the activityLogs of the second array item to the first array item by finding the matching element by vehicleno..
var json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
},{"vehicleno":"SV02","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
var json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}];
var jsonCont = json1.concat(json2);
var result = Object.values(jsonCont.reduce((acc, o)=>{
if(!acc.hasOwnProperty(o['vehicleno'])) {
acc[o['vehicleno']] = Object.assign({}, o);
} else {
acc[o['vehicleno']]['activityLogs'] = acc[o['vehicleno']]['activityLogs'].concat(o['activityLogs']);
}
return acc;
}, {}));
console.log(result);

Divide json array into json arrays based on a key

I have a json array like this:
[
{id:1, another_id:1},
{id:2, another_id:1},
{id:3, another_id:2}
]
Is it possible to divide this into json arrays based on the key another_id. In this case two json arrays should be created like this
jsonArr1 = [
{id:1, another_id:1},
{id:2, another_id:1}
]
jsonArr2 = [
{id:3, another_id:2}
]
another_id will be varying. Please help guys
If you do not know how many different result arrays you will have, you should not try to make a variable for each of them. Instead put them in an object, where each object property corresponds to a single possible value of another_id, and the value for it is the corresponding array.
You can achieve that with reduce:
var data = [{id:1, another_id:1},{id:2, another_id:1},{id:3, another_id:2}];
var result = data.reduce( (acc, obj) => {
acc[obj.another_id] = acc[obj.another_id] || [];
acc[obj.another_id].push(obj);
return acc;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you want different variables then you can build a function which will return filtered array based on the passed value. This will use Array.filter()
function formatData(check) {
var data = [{
id: 1,
another_id: 1
},
{
id: 2,
another_id: 1
},
{
id: 3,
another_id: 2
}
];
return data.filter(el => el.another_id === check);
}
jsonArr1 = formatData(1);
jsonArr2 = formatData(2);
console.log(jsonArr1);
console.log(jsonArr2);
I hope the code below will work for you. As this will create two separate json arrays Arr1 for id and Arr2 for another_id
data = [
{id:1, another_id:1},
{id:2, another_id:1},
{id:3, another_id:2}
];
console.log(data);
var Arr1 = [];
var Arr2 = [];
for(var i in data){
Arr1.push(data[i].id);
Arr2.push(data[i].another_id);
}

combining a names array with the values array in object es6

I'm using the influxdata API and that data comes back in this format:
{
"columns": [
"time",
"commit_time",
"expiration_time",
"kafka_consumer_group",
"kafka_offset_group",
"kafka_topic",
"kafka_topic_parition",
"message_metadata"
],
"name": "offsets",
"values": [
[
"2017-04-01T22:51:50.301Z",
"1491087110301",
"1491173510301",
"group-general-service-master",
0,
"replica-conversion-dev",
"6",
"NO_METADATA"
],
[
"2017-04-01T22:51:50.301Z",
"1491087110301",
"1491173510301",
"group-message-service-master",
2,
"service-dev",
"4",
"NO_METADATA"
],
[
"2017-04-01T22:51:50.303Z",
"1491087110303",
"1491173510303",
"group-general-service-mk-threadc",
7073,
"posted-dev",
"1",
"NO_METADATA"
]
]
}
The columns and values are separate but how can I combine the columns and values arrays together so that the values have the names with them:
{
[
{
"time": "2017-04-01T22:51:50.301Z",
"commit_time": "1491087110301",
"expiration_time": "1491173510301",
"kafka_consumer_group": "group-general-service-master",
"kafka_offset_group": 0,
"kafka_topic": "replica-conversion-dev",
"kafka_topic_partition": "6",
"message_metadata": "NO_METADATA"
}
]...
}
Your desired result is not a valid object/array notation.
Assuming you would like to get an array of object, you can try the following:
res.values.map(arr => ({
time: arr[0],
commit_time: arr[1],
expiration: arr[2],
// you get the idea...
}));
Or using array destructuring:
res.values.map(arr => {
var obj = {};
[
obj.time,
obj.commit_time,
obj.expiration,
// you get the idea...
] = arr;
return obj;
});
Assuming you need an array of objects, you could iterate the values array and for the keys the columns array and assign the objects to the collecting object. Then return a new array with the objects.
var data = { columns: ["time", "commit_time", "expiration_time", "kafka_consumer_group", "kafka_offset_group", "kafka_topic", "kafka_topic_parition", "message_metadata"], name: "offsets", values: [["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-general-service-master", 0, "replica-conversion-dev", "6", "NO_METADATA"], ["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-message-service-master", 2, "service-dev", "4", "NO_METADATA"], ["2017-04-01T22:51:50.303Z", "1491087110303", "1491173510303", "group-general-service-mk-threadc", 7073, "posted-dev", "1", "NO_METADATA"]] },
result = data.values.map(a => Object.assign({}, ...data.columns.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

convert array into an array of ojects

I have the following array list.
var data = [ "USA", "Denmark", "London"];
I need to convert it in this form
var data = [
{ "id" : 1, "label": "USA" },
{ "id" : 2, "label": "Denmark" },
{ "id" : 3, "label": "London" }
];
Can anyone please let me know how to achieve this.
Pretty easy using Array.map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
var formatted = data.map(function(country, index) {
return { id: (index + 1), label: country }
});
Simple version:
var convertedData = []
for (var i in data){
convertedData.push({id: i+1, label: data[i]});
}
data = convertedData; //if you want to overwrite data variable
You can use forEach to loop through the data array
var data = [ "USA", "Denmark", "London"];
var demArray =[];
data.forEach(function(item,index){
demArray.push({
id:index+1,
label:item
})
})
console.log(demArray)
JSFIDDLE
Underscore way (for old browsers without Array.map support):
var res = _.map(data, function(p, i){
return {id: i + 1, label: p};
});

Categories