0

So I have a JSON array of arrays

[ [ "2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic" ], [ "2016", "Mazda", "CX-5", "2.0", "Premium", "Manual" ] ] 

And essentially, I need to create a new JSON object using the values in the JSON array plus keys such as below:

{
  "root": {
    "cars": [
      {
        "Year": "2015",
        "Make": "Honda",
        "Model": "CR-V",
        "Engine": "1.5",
        "Submodel": "Turbo 7-Seater",
        "Transmission": "Automatic"
      },
      {
        "Year": "2016",
        "Make": "Mazda",
        "Model": "CX-5",
        "Engine": "2.0",
        "Submodel": "Premium",
        "Transmission": "Manual"
      }
    ]
  }
}

I'm new to JSON and Javascript. Can anyone provide some tips and guidance? Thank you!

1
  • There is no such thing as "JSON array of arrays", it's just an array of arrays. Something is either valid JSON or not:) Commented Sep 5, 2017 at 8:29

2 Answers 2

1

First of all these are Javascript arrays and objects and not JsonArray and JSONObject.

If the object properties are always the same, you can just map the array elements into respective objects:

var results = {
  "root": {
    "cars": arr.map(function(item) {
      return {
        "year": item[0],
        "make": item[1],
        "model": item[2],
        "engine": item[3],
        "submodel": item[4],
        "transmission": item[5]
      }
    })
  }
}

Demo:

var arr = [
  ["2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic"],
  ["2016", "Mazda", "CX-5", "2.0", "Premium", "Manual"]
];

var results = {
  "root": {
    "cars": arr.map(function(item) {
      return {
        "year": item[0],
        "make": item[1],
        "model": item[2],
        "engine": item[3],
        "submodel": item[4],
        "transmission": item[5]
      }
    })
  }
}

console.log(results);

Sign up to request clarification or add additional context in comments.

Comments

1

You can pass your original array to this function to get what you expected. As I know, you said that you're newbie in JS so my solution comes from simplest function (forEach of JS);

var rootObj = [ [ "2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic" ], [ "2016", "Mazda", "CX-5", "2.0", "Premium", "Manual" ] ];


function convert(arr) {
  var result = { root: { cars: [ ] } };
  arr.forEach(function(val) {
    result.root.cars.push({
      "Year": val[0],
      "Maker": val[1],
      "Model": val[2],
      "Engine": val[3],
      "Submodel": val[4],
      "Transmission": val[5]
    })
  });
  return result;
}

// You can test the result with this line of code
var output = convert(rootObj);
console.log('RESULT: ', JSON.stringify(output));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.