简体   繁体   中英

Converting object containing list of data to json array

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?

您可以使用var json = JSON.stringify(jsObject)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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM