How to take json response in an array - javascript

I am making a ajax request in jquery and in return getting the response but not as an array.
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}}
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
I want to merge the above two response and create an array something like this :
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
Please suggest how to do it. I want to take it in array and store it locally may be in config varaible get:[] and then access somewhat like config.get[data["seriesId"]].

you need to convert your response into an array of objects:
var response = [
{"ErrorCode":0,...},
{"ErrorCode":0,...},
{"ErrorCode":0,...},
]
in actual:
jsonResponse = [
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}},
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
]
then loop through:
var newArray = []
for(var i=0;i<jsonResponse.length;i++){ //loop through items
var stats = jsonResponse[i].SeriesSocialStats;
for(key in stats){ //loop through "SeriesSocialStats" numbers
newArray.push(stats[key]);
}
}
so it will be like:
newArray = [
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},
{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
]

You could do
var obj1 = {"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}};
var obj2 = {"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}};
var arr = [];
arr.push(ob1.SeriesSocialStats);
arr.push(ob2.SeriesSocialStats);

Best way convert your server response to array structure, like mentioned by Joseph, instead of doing double processing from object to array.

Related

Parsing JSON object in react js

I am getting API response as:
[{"subject1": "English", "subject1": "Maths"}]
I want to store the values (English and Maths) into an array without keys like:
subject = ["English", "Maths"]
maybe this solve your problem:
// if you have variable number of subject
let res = [{"subject1":"English", "subject2":"Maths"}]
let subjects = []
for(prop in res[0]){
subjects.push(res[0][prop])
}
console.log(subjects)
Does this solve your problem?
subject = [];
subject.push(Object.values(response));
Given an array of objects:
[{"subject1":"English"}, {"subject1":"Maths"}]
Use this:
let res = foo.map(e => e.subject1)
console.log(res) // prints ["English", "Maths"]

PUSH JSON items to array

I have this JSON string
{"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}
I want to push it's items to a jQuery array.
I already tried JSON.parse.
Normally I can push parameters like this:
MyArr.push(['Task','Hours per Day']);
MyArr.push(['Work','11']);
MyArr.push(['Eat','6']);
and so on.
How can I do the same with the JSON string?
Can you not just parse the JSON into an object and loop through?
var json = '{"Task": ["Hours per Day"],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}'
var obj = JSON.parse(json);
MyArr = []
for (var key in obj) {
MyArr.push([key, obj[key][0]])
}
console.log(MyArr)

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

How to merge the below arrays in javascript?

I have two arrays and I want to join them
function test()
{
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var args = [].slice.call(arguments);
args.join(',');
return args;
}
I am expecting the output as
[{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}]
But not able to. How to do it?
I have already tried with Concat() function of Javascript but it didn't helped.
N.B.~ As it can be assumed that there can be variable number of arrays in the Pack function.
Couldn't you do something like:
var newArray = [ { "Employees": arr1, "Departments": arr2 } ]
Try this:
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var json = {};
var jsonArr = [];
json.Employees = arr1;
json.Department = arr2;
jsonArr.push(json);
document.write(JSON.stringify(jsonArr));
From the expected JSON, what you need is neither "merging", nor "concatenation". You want to put an array inside an object.
What you want is below:
var output = [{
"Employees": arr1,
"Department": arr2
}];
Note that output is an array according to your expectation. Why you need an array is something I dont understand.
Ok, so i put a little fiddle together for you, Here
Most of your code stays the same, except I added this to your test function:
var myObjToMerge = [{Employees:[]},{Departments:[]}];
var res = Pack(myObjToMerge,arr1,arr2);
You need to give 'Pack' some object to merge the arrays to, so I created an arbritary array of objects modeled after your example. Note that this array of objects can come from anywhere and this method doesn't require it to be known ahead of time like some of the other examples.
Then I changed the 'Pack' function:
function Pack()
{
var objToMerge = arguments[0];
for(var i = 0;i<objToMerge.length;i++)
{
if(arguments.length > i+1)
{
var firstProperty = Object.keys(objToMerge[i])[0];
objToMerge[i][firstProperty]= arguments[i+1];
}
}
return objToMerge;
}
The idea here is that 'Pack' grabs the first argument, your object to merge the remaining arguments into. I would suggest using function parameters, but that is your call.
Then, I iterate through the objects in the objToMerge array (there are two objects: Employees and Departments).
I assume that the remaining items in arguments is in the correct order and I grab the next item in arguments and assign to to the first property in the object I am currently looped in.
The line:
var firstProperty = Object.keys(objToMerge[i])[0];
Will return the string value of the first property in an object. We then use this to set the next array in arguments to that property:
objToMerge[i][firstProperty]= arguments[i+1];
there are a great deal of assumptions here and ways to improve, but you can see that it works in the fiddle and you can improve upon it as needed.
function test() {
var arr1 = {"Employees" : [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
]};
var arr2 = {"Departments":[
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
]};
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var results = [];
arguments.forEach(function(element){
results.push(element);
});
return results;
}

Inverse object element order

What's the best way to inverse an order of json data?
var myObject = [
{"id":"001", "content":"content11111111111111"},
{"id":"002", "content":"content22222222222222"},
{"id":"003", "content":"content33333333333333"},
{"id":"004", "content":"content44444444444444"}
];
myJson = JSON.stringify(myObject);
var inverseMyJson = inverseOrder(myJson);
inverseMyJson ==>
[
{"id":"004", "content":"content44444444444444"},
{"id":"003", "content":"content33333333333333"},
{"id":"002", "content":"content22222222222222"},
{"id":"001", "content":"content11111111111111"}
]
Reverse it before you stringify it.
myObject.reverse();
myJson = JSON.stringify(myObject);
If you want to maintain the original order, then .slice() it first.
var reversed = myObject.slice().reverse();
myJson = JSON.stringify(reversed);

Categories

Resources