0

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?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
JpG
  • 774
  • 8
  • 22

5 Answers5

0

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

Marco Talento
  • 2,335
  • 2
  • 19
  • 31
0

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);
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
0

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.

Community
  • 1
  • 1
m-oliv
  • 419
  • 11
  • 27
0

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);
    }}
anis programmer
  • 989
  • 1
  • 10
  • 25
0

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);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78