how to convert json objects sepeted by comma into object - javascript

i have a string of 2 json object like this:
var param = '{"key1":"value1","key2":"value2"},{"key3":"value3"}';
how can i separate into 2 object like this in javascript..
var objA = {"key1":"value1","key2":"value2"};
var objB = {"key3":"value3"};

As simple as this - make an array from this objects
var param = '{"key1":"value1","key2":"value2"},{"key3":"value3"}';
var obj = JSON.parse('[' + param + ']');
var objA = obj[0];
var objB = obj[1];

Like this
var data = JSON.parse("[" + param "]");
objA = data[0];
objB = data[1];

You JSON string is wrong. Change your code to
var param = '[{"key1":"value1","key2":"value2"},{"key3":"value3"}]';
var jsonArr = JSON.parse(param);
for(var i in jsonArr) {
var jsonObj = jsonArr[i];
// jsonObj is your required object
}
See this FIDDLE here.

You could also do it with objects like this;
var param = '{"objA": {"key1": "value1","key2": "value2"}, "objB": {"key3": "value3"}}',
obj = JSON.parse(param),
objA = obj.objA,
objB = obj.objB;
console.log([obj, objA, objB]);
jsfiddle

Related

Transform simple string in a key: value array

I've the following string in the JavaScript:
test: hi,
otherTest: hiAgain
How can I transform in a key: value array?
var string = 'test: hi,otherTest: hiAgain';
var sets = string.split(","); //splits string by commas
var out = new Array(); //prepare the output array
for (var i=0; i<sets.length; i++) {
var keyval = sets[i].split(":"); //split by colon for key/val
out[keyval[0]] = keyval[1].trim(); //trim off white spaces and set array
}
Here is a quick example:
var str='test: hi,\notherTest: hiAgain';
var obj={};
var kvp=str.split('\n');
for(k=0;k<kvp.length;k++){
var temp=kvp[k].split(' ');
obj[temp[0]]=temp[1];
}
console.log(JSON.stringify(obj));
Here you are:
var data = ['test: hi', 'otherTest: hiAgain'];
var result = [];
$.each(data, function(index, value){
var keyValue = value.split(':');
var obj = {};
obj[keyValue[0].trim()] = keyValue[1].trim();
result.push(obj);
});
alert(JSON.stringify(result));
Hope this help.

Way to get assign the Object in jquery

I have Object obj in jquery
var obj = {};
I have the string str
var str = "passengerDetails[0].photo";
Now I am assigning this str as key in Object obj like below
obj = {str : "xx"} //means {"passengerDetails[0].photo" : xx} should come
But it is assigning as obj ={"str":"xx"};
What is the simple solution to this jquery Object code?
Try ,
var obj = {};
var str = "passengerDetails[0].photo";
obj[str] = "xx"; //it should work
console.log(obj); //Outputs --> Object { passengerDetails[0].photo="xx"}
var obj = {};
var str = "passengerDetails[0].photo";
obj[str] = "xx"; //it should work
console.log(obj); //Outputs --> Object { passengerDetails[0].photo="xx"}
//Thanks a lot to CodingAnt and this answer working like a boss

Converting a String to a Javascript Object

Am trying to convert the following string value into a javascript object
Example
string="name=usernamex&gender=boy&age=10&version_obj=1"
into
var user={ name:'username', gender:'boy',age:10,version_obj=1}
Can someone help me out
Looks like you want the querystring module: http://nodejs.org/api/querystring.html
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
with pure javascript..
var str="name=usernamex&gender=boy&age=10&version_obj=1";
var array = str.split('&');
var obj = {};
array.forEach(function(value){
var x = value.split('=');
obj[x[0]] = decodeURIComponent(x[1]);
});
console.log(obj);
If you don't want to use a module:
var strArr = string.split("&");
var user = {}, i = 0, n;
while(i<strArr.length) {
n = strArr[i].split("=");
if(n.length == 2)
user[decodeURIComponent(n[0])]
= decodeURIComponent(n[1]);
i++;
}

Is this javascript declaration an array or some kind of object

Can someone please explain how the following javascript code:
var temp = {};
temp[0] = "a"
temp[1] = "b"
temp[2] = "c"
if different from an array like
var temp = new Array();
or
var temp = []
I don't really understand if the first example "temp = {}" can be considered an array or is it some kind of object?
var temp = {}; is an object with representation like Object {0: "a", 1: "b", 2: "c"}
var temp = [] is an array with representation like ["a", "b", "c"]
while var temp = new Array(); is again the same thing like temp = []
More detailed information here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
The first one creates an object:
var temp = {};
The second one creates an array:
var temp = new Array();
In any case you can access them as they are an array:
var temp = {};
temp[1]="in object";
console.log(temp[1]);
same as
var temp = []
temp[1]="in array";
console.log(temp[1]);

Push an associative item into an array in JavaScript

How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle
To make something like associative array in JavaScript you have to use objects.
​
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
DEMO: http://jsfiddle.net/bz8pK/1/
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​
To get value you can use now different ways:
console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.
Another method for creating a JavaScript associative array
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.
// Order of entry altered
let obj = {}; // will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);
// Order of entry maintained for future iteration
obj = []; // will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

Categories

Resources