How to segregate the JSON response I'm getting [duplicate] - javascript

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
{
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
}
(Where TimeStamp1 andTimeStamp2 are valid time stamps)
I'm getting the above data using a Rest Service. I need to
Showcase it in a different manner. Have to convert it this way that I'll get the response in 2 variables called
Category = [TimeStamp1,TimeStamp2]
and
Data= [{
name: 'DB',
data: [100, 100]
}, {
name: 'Oracle',
data: [0, 100]
}]
Thanks in Advance

The first one is easy, just map the data array to one containing only the timestamps and pipe it into a Set
const Category = Array.from(new Set(obj.Data.map(datum => datum.TimeStamp)))
The second will require you to reduce the data to a map of Rsrc to a status array which you can then transform into an array
const obj = {"Data":[{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"0","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"100","TimeStamp":"TimeStamp2"},{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp2"}]}
const Data = Array.from(obj.Data.reduce((map, datum) => {
let data = map.get(datum.Rsrc) || []
return map.set(datum.Rsrc, data.concat(datum.status))
}, new Map())).map(entry => ({
name: entry[0],
data: entry[1]
}))
console.info('Data', Data)

var input ={
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
};
var data= input.Data;
var Category =[];
var Data =[];
var DataIndex = [];
data.forEach(function(i)
{
if(Category.indexOf(i.TimeStamp)==-1) Category.push(i.TimeStamp);
var idx=DataIndex.indexOf(i.Rsrc)
if(idx==-1) {
DataIndex.push(i.Rsrc);
Data.push({name:i.Rsrc,data:[i.status]});
} else {
Data[idx].data.push(i.status);
}
});
console.log(Category);
console.log(Data);

I looped over your data and built the two new arrays. I used a third rsrc array to help to determine which position in the data array to add new items too.
var test = {
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": 'TimeStamp2'
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp2'
}
]
};
var category = [];
var data = [];
var rsrc = [];
test['Data'].forEach(function( item ){
if( category.indexOf( item['TimeStamp'] ) === -1 ){
category.push( item['TimeStamp'] );
}
if( rsrc.indexOf( item[ 'Rsrc' ] ) === -1 ){
rsrc.push( item[ 'Rsrc' ] );
}
var pos = rsrc.indexOf( item[ 'Rsrc' ] );
// set as itself or an object if it's not yet been set
data[pos] = data[pos] || {};
data[pos].name = item[ 'Rsrc' ];
data[pos].data = data[pos].data || [];
data[pos].data.push( item.status );
});
console.log( category );
console.log( data );
Edit fixed issue with repeated categories, thanks to #yashgarg1232

Related

How can i filter result if i have array in body

i have a payload
{
"category": "Mobile",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"1",
"2",
"3"
]
}
i want to find all object which have rating 1 or 2 or 3 and also have any location
Basically i am creating a filter for an ecommerce store i which we will get multiple location and multiple ratings as well so we will return only those object which have matched property. i am attaching a screenshot of UI for better understanding.
i want to run this filter with multiple location and multiple checked checkbox
You can do create a filter dynamically:
const { category, price, location, rating } = req.body;
const filter = {};
if (category) filter.category = category;
if (price) filter.price = { $gte: parseInt(price.from, 10), $lte: parseInt(price.to, 10) };
if (location?.length) filter.location = { $in: location };
if (rating?.length) filter.rating = { $in: rating };
const data = await Collection.find(filter);
If you want to filter your objects, you should use filter() from your array :
const arr = [{
"category": "Mobile1",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"1",
"2",
"3"
]
},
{
"category": "Mobile2",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"2",
"3"
]
}];
const result = arr.filter(el => el.rating.includes("1") || el.rating.includes("2") || el.rating.includes("3"));
console.log(result);

How to access JSON array elements from Input to output which are similar in structure

I have to transfrom input json to output json message using javascript
Below are input and output test samples
Input
[{
"Id": "123",
"Address": "12",
"Cadre": "LOLOL"
"Meeting": {"Output": [
{
"Date": "2020-08-13T15:00:00Z",
"comment": "Working"
},
{
"timestamp": "2020-08-13T10:03:01Z",
"comment": "Learning"
},
]}
},
{
"Id": "345",
"Address": "14",
"Cadre": "Loop"
"Meeting": {"Output": [
{
"Date": "2020-12-12T18:27:00Z",
"comment": "Working"
},
{
"timestamp": "2020-11-22T14:53:01Z",
"comment": "Learning"
},
]}
}
]
Output also should remain same, with out changes to other fields except the array in "Meeting/Output/comment" field.
Output
[{
"Id": "123",
"Address": "12",
"Cadre": "LOLOL"
"Meeting": {"Output": [
{
"Date": "2020-08-13T15:00:00Z",
"comment": "NOt known"
},
{
"timestamp": "2020-08-13T10:03:01Z",
"comment": "Taken"
},
]}
},
{
"Id": "345",
"Address": "14",
"Cadre": "Loop"
"Meeting": {"Output": [
{
"Date": "2020-12-12T18:27:00Z",
**"comment": "Should Not be"**
},
{
"timestamp": "2020-11-22T14:53:01Z",
**"comment": "Help///A"**
},
]}
}
]
I have taken "for" loop to iterate on Input payload array object and retrieved the "Meeting" object made necessary changes
I have tried this
session.input.readAsJSON(function(readAsJSONError, payload) {
var incomingDataLength = payload.length;
for(var i=0; i<incomingDataLength; i++){
var reqArr = payload.Meeting.Output;
if(reqArr === null || reqArr === '' || reqArr === undefined) {
console.log("Do something");
} else {
var reqArrLength = payload.Meeting.Output.length;
for(var i=0; i<reqArrLength; i++){
reqArrLength[i].comment= callsomefunction(reqArrLength[i].comment);
}
}
}
});
Could you please suggest me on this to proceed.
The simplest way to do it is by using Array.map
var output = input;
output.Meeting.Output = input.Meeting.Output.map(item =>
{
delete item.comment;
return item;
});
If you already have the array - then use the Array.forEach
input.Meeting.Output.forEach(item =>
{
delete item.comment;
});

Handle Array of Object manipulation

Below I have an array of objects
var data = [{
"time": "1572024707.4763825",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}, {
"time": "1572024708.3903246",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
}]
How can I restructure it to remove the repeating id's with the oldest time
I tried to pull all the unique IDs from the array so I can loop through the data array but then the code started to get too long.
data.forEach(item => {
IDs.push(item.id);
});
var unqIDs = [...new Set(IDs)];
console.log(unqIDs);
the output should look like this
outPutShouldBe = [{
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
},{
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}
]
Create an object mapping ids to the item w/ the earliest time of those with that id:
var keydata = {};
data.forEach(item=>{
var p = keydata[item.id];
if ( !p || p.time>item.time ) {
keydata[item.id] = item;
}});
Now gather up the values in that object:
var newdata = [];
for ( var k in keydata ) {
newdata.push(keydata[k]);
}
or the more elegant (thanks, #TulioF.):
var newdata = Object.values(keydata)
Using forEach() find() filter() and filter() to decide which element to return
var data = [{"time": "1572024707.4763825","rssi": "32","id": "77777"},{"time": "1572024709.0991757","rssi": "32","id": "77777"}, {"time": "1572024704.4570136","rssi": "32","id": "555555"}, {"time": "1572024708.3903246","rssi": "32","id": "77777"}, {"time": "1572024699.7132683","rssi": "32","id": "66666"}]
let resultsArray = []
data.forEach(obj=>{
const foundObj = resultsArray.find(data => data.id === obj.id)
if(foundObj && new Date(foundObj.time) > new Date(obj.time)){
const filteredArray = resultsArray.filter(data => data.id === obj.id)
resultsArray = [...filteredArray , foundObj]
} else if (!foundObj){
resultsArray.push(obj)
}
})
console.log(resultsArray)
You coud take an object as hash table and get the values directly.
var data = [{ time: "1572024707.4763825", rssi: "32", id: "77777" }, { time: "1572024709.0991757", rssi: "32", id: "77777" }, { time: "1572024704.4570136", rssi: "32", id: "555555" }, { time: "1572024708.3903246", rssi: "32", id: "77777" }, { time: "1572024699.7132683", rssi: "32", id: "66666" }],
result = Object.values(data.reduce((r, o) => {
if (!r[o.id] || +r[o.id].time > +o.time) r[o.id] = o;
return r;
}, {}));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
use lodash to sort the array in descending order or ascending order as per your need (desc, asc) and get the zeroth object. try something like this. filter and orderBy
var data = [{
"time": "1572024707.4763825",
"rssi": "32",
"id": "77777"
}, ....];
let idsSet = new Set();
data.map(item=> idsSet.add(item.id));
let idsArr = Array.from(idsSet);
let newArr = [];
idsArr.map(id=>{
let tempArray = data.filter(item => item.id === id);
return newArr.push((_.orderBy(tempArray, ['time'],['desc']))[0]);
} )
console.log(newArr);
console output
[ {
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}, {
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
}];
Here you can do something like this :
let existMap = {};
data.filter(val => {
if((val.id in existMap) && (val.time>existMap[val.id])) return;
else{
existMap[val.id] = val.time;
return true;
}
})
console.log(result)
The condition can be changed based on requirement. just want to reference for your problem.

Hierarchical json to flat with parent ID

I have Hierarchical JSON and want to convert to flat JSON without parent child.
vm.str = [
{
"s_gid": 0,
"title": "scholastic Master List 2016",
"nodes": [
{
"Id": "1",
"templateId": "1",
"s_gid": "10",
"m_s_p_id": "1",
"subject_group_name": "xxxxxxx",
"parent_id": "1",
"sname": "",
"nodes": [
{
"Id": "2",
"templateId": "1",
"s_gid": "100",
"m_s_p_id": "0",
"subject_group_name": "abc",
"parent_id": "10",
"sname": "",
"nodes": [
{
"Id": "3",
"templateId": "1",
"s_gid": "1000",
"m_s_p_id": "0",
"subject_group_name": "efg",
"parent_id": "100",
"sname": ""
}
]
}
]
}
]
}
]
what to convert to new vm.str2 = [] as flat, all nodes at same level without nodes ... sub nodes..
You can use recursive function to return one array of objects
var arr =[{"s_gid":0,"title":"scholastic Master List 2016","nodes":[{"Id":"1","templateId":"1","s_gid":"10","m_s_p_id":"1","subject_group_name":"xxxxxxx","parent_id":"1","sname":"","nodes":[{"Id":"2","templateId":"1","s_gid":"100","m_s_p_id":"0","subject_group_name":"abc","parent_id":"10","sname":"","nodes":[{"Id":"3","templateId":"1","s_gid":"1000","m_s_p_id":"0","subject_group_name":"efg","parent_id":"100","sname":""}]}]}]}]
function flatten(data) {
var result = [];
data.forEach(function(o) {
var obj = {}
for(var e in o) {
(Array.isArray(o[e])) ? result.push(...flatten(o[e])) : obj[e] = o[e];
}
result.push(obj)
})
return result;
}
console.log(flatten(arr))
You could use Array.prototype.reduce() plus recursion for this task:
function getNodes(inputArr) {
return inputArr.reduce(function (prev, value) {
return prev.concat(
[ value ],
(value.nodes ? getNodes(value.nodes) : [])
);
}, []);
}
If you still want to remove nodes, you could either use Array.prototype.map or even Array.prototype.each:
output = output.map(function (value) {
value.nodes = undefined;
return value;
});

I am having a hard time retrieving data from json object

{
"formname": ["Myapname", {
"operation": ["add", {
"values": {
"confirm_code": "12345",
"ID": 222333333,
"user_id": "10000"
},
"status": "Success"
}]
}]
}
I have tried this below:
posting.done(function( data ) {
var obj = JSON.parse(data);
console.log(obj["ID"]);
});
});
But I am not getting back anything all I see undefined
can someone assist me with what am doing wrong
ID is not a property of obj, it's property of it's nested object. You can get it using obj.formname[1].operation[1].values.ID
var obj = {
"formname": ["Myapname", {
"operation": ["add", {
"values": {
"confirm_code": "12345",
"ID": 222333333,
"user_id": "10000"
},
"status": "Success"
}]
}]
};
console.log(
obj.formname[1].operation[1].values.ID
)

Categories

Resources