0

i am trying to construct a JSON request that has two arrays in it, this is the end result i am looking for:

[
    {
        "Policy": {
            "Channel": "online",
            "Credit Score": "20000",
            "Car": [
                {
                    "Age": "28",
                    "AnnualMiles": "15000",
                    "CarAge": "3",
                    "Young Driver": "1"
                }
            ]
        }
    }
]

i am trying to push two objects in the JSON Arrays, one into the root array (i attached this object to a variable called result):

 {
        "Channel": "online",
        "Credit Score": "20000"
    }

and the other one into the sub array (i attached this object to a variable called result2):

{
        "Age": "28",
        "AnnualMiles": "15000",
        "CarAge": "3",
        "Young Driver": "1"
    }

The code i am trying to use is:

policy=new Array() 
policy.car=new Array() 
policy.push(result)
policy.car.push(result2)
console.log(policy)
console.log(JSON.stringify(policy))
    response.status(200).json(policy)

i see that the JS object (policy) is constructed in the structure i was looking for, however the JSON i am getting back is just the first level:

[
    {
        "Channel": "online",
        "Credit Score": "20000"
    }
]

what am i missing here?

Ofer B
  • 101
  • 1
  • 10
  • You want `policy` to be an object, yet you define it as an array. This should do what you want `[{policy:{...result, car:[result2]}}]`. – str Dec 16 '20 at 11:08
  • 1
    Does this answer your question? [What is array literal notation in javascript and when should you use it?](https://stackoverflow.com/questions/1094723/what-is-array-literal-notation-in-javascript-and-when-should-you-use-it) – str Dec 16 '20 at 11:12
  • https://stackoverflow.com/questions/9699064/what-do-curly-braces-in-javascript-mean – str Dec 16 '20 at 11:12
  • @str thank you for your response, what do the three dots mean in the syntax? – Ofer B Dec 16 '20 at 11:26
  • [{policy:{...result, car:[result2]}}] this does the trick, but is there a way to do it with push statements? – Ofer B Dec 16 '20 at 11:35
  • https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript – str Dec 16 '20 at 12:31
  • `const res = [{policy:{...result, car:[]}}]; res[0].policy.car.push(result2)` – str Dec 16 '20 at 12:32

1 Answers1

0

"Car" array in your JSON is part of the "Policy" object, so the "Car" array should be defined in the "result" object which would be pushed to root array like this:

policy = new Array();

let result = {
    "Channel": "online",
    "Credit Score": "20000"
}
let result2 = {
    "Age": "28",
    "AnnualMiles": "15000",
    "CarAge": "3",
    "Young Driver": "1"
}
result.car=new Array();
result.car.push(result2);

policy.push(result);
Saurabh
  • 378
  • 2
  • 9