I have a json file array with data and I want to use it in a jquery array.
My json file is like this;
[{"id":"1","value":"0.00","score":"a"},
{"id":"2","value":"0.00","score":"c"},
{"id":"3","value":"12.56","score":"e"}]
and then my jquery array outcome i want should be like this (but missing the score and value data.
var setup = [
{
"type": "single",
"subtype": {
"type": "Point",
"score": use 'score' of the json file
},
"properties": {
"text": use 'value' of the json file,
"height": 60
}
},
{
"type": "single",
"subtype": {
"type": "Point",
"score": use score of the json file
},
"properties": {
"text": use value of the json file,
"height": 60
}
}
];
Below I made an attemp to set up a jquery array but i am mnot so good in this. I think i have to use a double $each? but how do I make the array?
var setup = [];
// FETCHING DATA FROM JSON FILE
$.getJSON("results.json", function(data) {
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
var test = "";
$.each(value, function(index, obj) {
});
});
setup.push(setup);
});
Thanks in advance:)
You could use Array.prototype.map()
method to get the result.
const data = [ { id: '1', value: '0.00', score: 'a' }, { id: '2', value: '0.00', score: 'c' }, { id: '3', value: '12.56', score: 'e' }, ]; const ret = data.map((x) => ({ type: 'single', subtype: { type: 'Point', score: x.score, }, properties: { text: x.value, height: 60, }, })); console.log(ret);
You can use one each loop and pass the object with the elements you need. Check the below example:
var jsonData = [{ "id": "1", "value": "0.00", "score": "a" }, { "id": "2", "value": "0.00", "score": "c" }, { "id": "3", "value": "12.56", "score": "e" } ] var setup = []; // FETCHING DATA FROM JSON FILE $.each(jsonData, function(key, value) { var test = ""; d = { "type": "single", "subtype": { "type": "Point", "score": value.score }, "properties": { "text": value.value, "height": 60 } }; setup.push(d) }); console.log(setup)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.