Converting object containing list of data to json array - javascript

My for loop looks like this,
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(myObj[key]);
}}
output on console looks like this,
car1
car2
car3
i want to convert this data something like this,
$scope.myArray = [{"cars":car1}, {"cars":car2}, {"cars":car3}]
how can I convert it this way in javascript?

You can use var json = JSON.stringify(jsObject) and var jsObject = JSON.parse("json string")

Just iterate over object and push it into array:
var myObj = data.response.carTypes;
var myArr = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
myArr.push(myObj[key]);
}
}
console.log(myArr);

You can convert the array to JSON using var myJsonArray = JSON.stringify(myArray).
If you're doing this conversion in an older browser, you can use a script.
In order to get your array from the JSON you created, you can use:
var myArray = JSON.parse(myJsonArray)
Also, bear in mind that when you use the same key for several objects in your JSON, the last key with the same name is the one that is going to be used.

Here you have to use javascript object.
say
$scope.myArray = [];
var carlist.cars="";
var carlist={};
carlist is a object which cars is a property
then you can try this way:
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carlist.cars=myObj[key];
myArray.push(carlist);
console.log(myArray);
}}

You just need to create a new array and push a new object to it in each iteration:
$scope.myArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
$scope.myArray.push({cars:myObj[key]});
}
};
Demo:
var myObj = {
a: "Car1",
b: "Car2",
c: "Car3"
};
var carsArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carsArray.push({cars:myObj[key]});
}
};
console.log(carsArray);

Related

Push object into array without key in javascript

I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}
It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])
Try this
newArr.push(...myobj);

How to make another nested json with keys from a nested json

The strings that are coming from source is coming in fragmented JSON object in JSON object.I want to convert this JSON structure to a another simple JSON structure:
{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}
could it changed to be like
{
"key":"nestA"
"a":"link"
"b":711
},
{
"key":"nestB"
"a":"img"
"b":165
}
//convert json string into an object
var json = '{"nestA":{"a":"link","b":2711},"nestB":{"a":"img","b":4165}}'
var sourceObject = JSON.parse(json);
//get a list of the object keys
var keys = Object.keys(sourceObject);
//create a new array to hold our output
var array = [];
//loop through our keys adding them to our array in the format we want
keys.forEach(function(key){
var nest = sourceObject[key];
nest.key = key;
array.push(nest);
});
//convert our array back to json
var result = JSON.stringify(array);
console.log(result);
var json = [{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}];
var arr = [];
json.forEach(function(v) {
Object.keys(v).forEach(c => arr.push(v[c]));
arr.forEach((b, x) => b['key'] = Object.keys(v)[x]);
});
console.log(arr);
Working with JSON it's best to parse it first, modify it and then turn it back into JSON:
var orgObj = JSON.parse(orgJSON);
var newArr = [];
for( var key in orgObj){
var temp = { key: key };
Object.assign( temp, orgObj[key]);
newArr.push(temp);
}
var newJSON = JSON.stringify(newArr);
Assuming an array was what you were going for. Please clean up your desired JSON.
Without using es6 the for loop could be:
for( var key in orgObj){
orgObj[key].key = key;
newArr.push( orgObj[key] );
}
but orgObj would get modified.

Key Value pair from an array with key Value pair in javascript

I have an array like this:
var arrayTemp = [
{"0":["Z",59]},
{"1":["D",53]},
{"2":["6",26]},
{"3":["3",19]},
{"4":["Y",10]},
{"5":["H",7]},
{"6":["G",5]},
{"7":["2",5]}
];
I need an output similar to the below one,
var arrayTemp = [
{"Z":59},
{"D":53},
{"6":26},
{"3":19},
{"Y":10},
{"H":7},
{"G":5},
{"2":5}
];
How do I achieve this? I would like this to be achieved with the help of json, underscore or JavaScript.
Using Array.prototype.map() you could iterate trough each element of the original array and create the required objects, returning them as new elements in a new array.
var newArray = arrayTemp.map(function(e, index) {
var x = {};
x[e[index][0]] = e[index][1];
return x;
})
DEMO - Using Array.prototype.map() to create the new array
Something like this:
var newArray = arrayTemp.map(function(e) {
var index = Object.keys(e).shift(),
innerElement = e[index],
ret = {};
ret[innerElement[0]] = innerElement[1];
return ret;
})
JsFiddle to test.
With underscore:
var newArr = _.map(arrayTemp, function(item){
for (var i in item){
var o = {};
o[item[i][0]] = item[i][1];
return o;
}
});
Although #François_Wahl's solution is the better one in my esteem using the native Array.prototype.map().

How can I read the property in a JavaScript object?

var stats = JSON.parse(xmlhttp.responseText);
for (index = 0; index <= top; ++index) {
console.log(stats[index]);
}
Return object:
Object {nick: "Okorok", uniq: "STEAM_0:0:XX", teamkill: 4, damage: 619592, deaths: 1727…}
How do I read a property?
If I try "console.log(stats[index]['nick']);", I have an error: "Cannot read property 'nick' of undefined ".
See if stats is an Array of Objects or just a simple Object.
If this is just a simple Object, so you directly use:
console.log(stats['nick']);
or
console.log(stats.nick);
Ok, if it is Object with Objects try this:
for ( key in stats)
{
console.log(stats[key].nick);
}
A sample here: http://jsfiddle.net/2d6bb/3/
I think you have somrthing like an array of objects, like:
stats = [{},{},{},...];
if it is so you can do this:
var stats = JSON.parse(xmlhttp.responseText);
for (var index = 0; index<stats.length;index++){
for (var key in stats[index]) {
console.log(stats[index][key]);
}
}
and if not, it would be an object of objects, like:
stats = { "stat1": {}, "stat2": {}, "stat3": {}, ...];
then you can do this:
var stats = JSON.parse(xmlhttp.responseText);
for (var index in stats){
for (var key in stats[index]) {
console.log(stats[index][key]);
}
}
or it is just simply a single object like:
stats = {}
then you can simply try:
for (var key in stats) {
console.log(stats[key]);
}
so if it is an array-like object you have to different ways, first you can use underscore.js:
stats = _.toArray(stats);
or if you don't want to use the underscore.js the other way is:
var stats2 = []
for (var key in stats) {
stats2.push(key);
}
stats = stats2;

JSON.stringify serializes to [[]]

If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));​

Categories