I need to create an object in this format by using JavaScript.
var results = {
"A-1": [
{ "object": "daily", "type": "when", "field": "Period" }
],
"A-2": [
{ "object": "weekly", "type": "when", "field": "Period" }
],
"A-3": [
{ "object": "monthly", "type": "when", "field": "Period" }
],
"B-1": [
{ "object": "Boston", "type": "who", "field": "City" },
{ "object": "AG", "type": "what", "field": "region" },
{ "object": "L1", "type": "where", "field": "Level" }
],
"B-2": [
{ "object": "New York", "type": "who", "field": "City" },
{ "object": "AG", "type": "what", "field": "region" },
{ "object": "L2", "type": "where", "field": "Level" }
],
"B-3": [
{ "object": "Paris", "type": "who", "field": "City" },
{ "object": "EURO", "type": "what", "field": "region" },
{ "object": "L1", "type": "where", "field": "Level" }
],
"B-4": [
{ "object": "Boston", "type": "who", "field": "City" },
{ "object": "AG", "type": "what", "field": "region" },
{ "object": "L2", "type": "where", "field": "Level" }
]
};
var periodList = "daily,weekly,monthly";
The B- section key values are returned from web services in JSON format as shown below:
[
{ "object": "Boston", "level": "L1", "region": "AG" },
{ "object": "Paris", "level": "L1", "region": "EURO" },
{ "object": "Boston", "level": "L2", "region": "AG" },
{ "object": "China", "level": "L1", "region": "AP" },
{ "object": "New York", "level": "L2", "region": "AG" }
]
Each B- object contains the city, region and level arrays.
Please help how to create this structure dynamically?
1 Answer 1
Just use two simple loops:
var results = {};
var periods = periodList.split(",");
for (var i=0; i<periods.length; i++)
results["A-"+(i+1)] = [
{"object": periods[i], "type": "when", "field": "Period"}
];
for (var i=0; i<json.length; i++)
results["B-"+(i+1)] = [
{"object": json[i].object, "type": "who", "field": "City"},
{"object": json[i].region, "type": "what", "field": "region"},
{"object": json[i].level, "type": "where", "field": "Level"}
];
There is no arbitrary nesting, so you don't need recursion or anything heavy.
answered May 6, 2016 at 0:04
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Daniel Kucal
periods.lenght one more typoMonica
Thank you for your quick solution. I am much appreciated.
Monica
Hi, What if I need to add the section A to each of B section instead? How can I show my new format?
lang-js
Chinabe in your desired JSON output? Also, is keyojbectin the web service returned JSON a typo in your question?A-key-array pairs constant?