The format you're trying to create is not syntactically correct, you can't have key/value pairs in an array. However, you could use an object instead:
var obj = {};
["One", "TWO", "THREE"].forEach(function(v) {
obj[v] = 'CNX';
});
console.log(obj);
Answer from Rory McCrossan on Stack OverflowThe format you're trying to create is not syntactically correct, you can't have key/value pairs in an array. However, you could use an object instead:
var obj = {};
["One", "TWO", "THREE"].forEach(function(v) {
obj[v] = 'CNX';
});
console.log(obj);
The following format:
[
"One": "CNX",
"TWO": "CNX",
"THREE": "CNX"
]
Is not a valid one. It should be:
{
"One": "CNX",
"TWO": "CNX",
"THREE": "CNX"
}
To do that:
var text = ["One", "TWO", "THREE"];
var myarray = {};
for (var i = 0; i < text.length; i++) {
var name = text[i];
var toaddstr = 'CNX'
myarray[name] = toaddstr;
}
console.log(myarray);
Whether you choose the first or the third option depends on your use case. If you are modeling many different instances of the same type of thing, choose the first. For example, you have a list of people. If you are modeling many different attributes of one thing, choose the third. You can have repeated keys in the first format, but not in the third.
The second option is terrible, and I've yet to find an appropriate use case for it. The reason it's terrible, in addition to being more verbose, is that for single-level JSON, it breaks most libraries' automatic conversion to a dictionary/map. For deeply-nested JSON, it breaks the XPath-like query interface.
This makes it a pain to work with. And if you don't know your keys at compile time, you will want a dictionary or XPath interface, because you won't be able to convert it to a class. It may not seem like a big deal now, but the longer you have a data format, the harder it will be to change.
You say these are key / value pairs. In that case, use #3: dictionary of key / value pairs.
If these are not key / value pairs, then don't call them "keys" and "values" and use #2, an array of dictionaries with arbitrary contents.
Structure #1 is just daft unless you need key / value pairs but also their order. Which you rarely do.
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
Use map like so:
const arr = data.map(city => city.name + ", " + city.country);
arr will be a new array of the same length as data where each city object in data is mapped to the string city.name + ", " + city.country.
Demo:
const data = [ {country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"}, {country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"}, {country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"}, {country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"} ];
const arr = data.map(city => city.name + ", " + city.country);
console.log(arr);
const data = [{country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"},
{country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"},
{country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"},
{country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"}]
const arr = data.map(i => `${i.name} , ${i.country}`);
console.log(arr)
I would use the js map method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
let output = this.responseStatus.dynaModel.map(item => item.map);
dynaModel is an array of objects so you can loop throuh it and pick map property (which is an object also) of every object in and put that object into output array.
let response = {
"dynaModel": [
{
"map": {
"UNIT/SUBUNIT": "EAS",
"SUBUNIT/ISU/GEO": "Africa",
"'APR-16'_REVENUEUSD-$": "$805,298",
"'APR-16'_COSTUSD-$": "$701,026",
"'APR-16'_GMINR-RSUSD-$": 12.95,
"'Total'_REVENUEUSD-$": "$805,298",
"'Total'_COSTUSD-$": "$701,026",
"'Total'_GMINR-RSUSD-$": 12.95
}
},
{
"map": {
"UNIT/SUBUNIT": "fgdfg",
"SUBUNIT/ISU/GEO": "dfgdfg",
"'APR-16'_REVENUEUSD-$": "$58,",
"'APR-16'_COSTUSD-$": "$32,",
"'APR-16'_GMINR-RSUSD-$": 43.98,
"'Total'_REVENUEUSD-$": "$58,",
"'Total'_COSTUSD-$": "$32,",
"'Total'_GMINR-RSUSD-$": 43
}
}
]
}
let output = new Array();
for (let object of response.dynaModel) {
output.push(object.map);
}
console.log(output);
prints:
[ { 'UNIT/SUBUNIT': 'EAS',
'SUBUNIT/ISU/GEO': 'Africa',
'\'APR-16\'_REVENUEUSD-$': '$805,298',
'\'APR-16\'_COSTUSD-$': '$701,026',
'\'APR-16\'_GMINR-RSUSD-$': 12.95,
'\'Total\'_REVENUEUSD-$': '$805,298',
'\'Total\'_COSTUSD-$': '$701,026',
'\'Total\'_GMINR-RSUSD-$': 12.95 },
{ 'UNIT/SUBUNIT': 'fgdfg',
'SUBUNIT/ISU/GEO': 'dfgdfg',
'\'APR-16\'_REVENUEUSD-$': '$58,',
'\'APR-16\'_COSTUSD-$': '$32,',
'\'APR-16\'_GMINR-RSUSD-$': 43.98,
'\'Total\'_REVENUEUSD-$': '$58,',
'\'Total\'_COSTUSD-$': '$32,',
'\'Total\'_GMINR-RSUSD-$': 43 } ]
You can use map() function to iterate on them and return an array you want.
let json = [{"key":"Jan","value":"400"},{"key":"Apr","value":"500"},{"key":"Aug","value":"24058.635"},{"key":"Sep","value":"2160"},{"key":"Nov","value":"115425"},{"key":"Dec","value":"32570"}];
let obj = json.map(item => [item['key'], item['value']]);
console.log(obj);
You could do something like this.
var input = [{
"key": "Jan",
"value": "400"
}, {
"key": "Apr",
"value": "500"
}, {
"key": "Aug",
"value": "24058.635"
}, {
"key": "Sep",
"value": "2160"
}, {
"key": "Nov",
"value": "115425"
}, {
"key": "Dec",
"value": "32570"
}];
var output = input.map(function(obj) {
return [obj.key, obj.value]
});
console.log(output);
The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:
new JSONArray()
.put(new JSONObject()
.put("name", "cases")
.put("value", 23))
.put(new JSONObject()
.put("name", "revenue")
.put("value", 34))
.put(new JSONObject()
.put("name", "1D5")
.put("value", 56))
.put(new JSONObject()
.put("name", "diag")
.put("value", 14))
.toString();
Once you have the final array, call toString on it to get the output.
Try to use gson if you have to work a lot with JSON in java. Gson is a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Here is a small example:
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]
You have to create a JSONObject, put it in a JSONArray and then add it to your first JSONObject, try the following code:
JSONObject aux=new JSONObject();
aux.put("expectedDisbursementDate","21 December 2018");
aux.put("principal", "1000");
aux.put("approvedPrincipal", "1000");
JSONArray arr = new JSONArray();
arr.put(aux);
loan.put("disbursementData",arr);
Logic would be the same for any library but the syntax will differ. I am using thecom.google.gson library.
Create object to be placed in the array :
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("expectedDisbursementDate", "21 December 2018");
jsonObj.addProperty("principal", "2000");
jsonObj.addProperty("approvedPrincipal", "2000");
Create the array and add the object to it :
JsonArray jsonArray = new JsonArray();
jsonArray.add(jsonObj);
Add the array to the original json object :
JsonObject loan = new JsonObject();
loan.addProperty("clientId", "1");
loan.addProperty("productId", "1");
loan.addProperty("disbursementData", jsonArray.toString());
This is not the ideal way to create an object, but you can skip the key, create an object with the key/value using the current index (i), and push it to the result (orderInputObjects):
const orderInputArray = ["key1", "value1", "key2", "value2"];
const orderInputObjects = [];
orderInputArray.forEach(function(v, i, a) {
if(i % 2) orderInputObjects.push({ [a[i - 1]]: v });
});
console.log(orderInputObjects);
You can use a simple for loop and increment by 2 instead of 1
function arrayToKeyValue(array) {
let updated = [];
for (let i = 0; i < array.length; i += 2) {
const key = array[i];
const value = array[i + 1];
updated.push({ key: value });
}
return updated;
}