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);
Related
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
I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)
I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.
I create JSON object as:
var myJsonObject = JSON.stringify(objectString)
How I can add another item into myJsonObject??
myJsonObject is now a string you cannot add anything to it again until you change it back into a JSON object.
So you can technically do:
var myJsonObject = JSON.parse(myJsonObject); //change to obj
myJsonObject.somethingnew = true; //add something
myJsonObject = JSON.stringify(myJsonObject); //change back to string
Looks like you're re-serializing the string rather than parsing it.
var myJsonObject = JSON.parse(objectString);
then you can add a new item by using
myJsonObject['newItemName'] = newValue;
Hope that's clear.
If you mean you want to have an array of objects, you can do it like this:
//create an array with the result of your object (see the [] characters)
var myJsonArrayObject = JSON.stringify( [ objectString ] );
//add a new element to the array: parse the JSON, push the new element and stringify again:
JSON.stringify( JSON.parse( myJsonArrayObject ).push( newObject ) );
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.