Iterate JSON array with maps using jquery - javascript

Below is the JSON array i am receiving from the dynamo DB and i need to iterate the same display the results in a table. where M is Map with more than one values. Can any one help me with the Jquery and HTML part of it.
{
"Item": {
"Subscriptions": {
"M": {}
},
"NetworkID": {
"S": "1234"
},
"SubscriptionARNs": {
"SS": [
" "
]
}
}
}

Here is all the data in details you can do what you want to do with it, first one deal with it as a hash, second as a string, third as an array:
data = {....}
item = data["Item"]
Subscriptions = item["Subscriptions"]
NetworkID = item["NetworkID"]
SubscriptionARNs = item["SubscriptionARNs"]
// for Subscriptions Data
M = Subscriptions["M"]
keys = Object.keys(M)
for(i = 0;i<keys.length;i++){
console.log(keys[i] +"="+M[keys[i]])
}
// for Network Data
S = NetworkID["S"]
// for SubscriptionARNs Data
SS = SubscriptionARNs["SS"]
for(i = 0;i<SS.length;i++){
console.log(SS[i])
}

Related

How to get value from a nested array by index in javascript?

I am new to JS, I have been working on this case for 2 days now, experimenting how to get a value from a nested array by index.
This is my original array return from a server:
[
{
"customer":{
"c_id":"4047",
"quote_id":"PO3640",
"post_date":"2021-01-25 06:26:01",
"first_name":"Brett",
"last_name":"H",
"email":"brett#hafs.com.au",
"phone":"0419778645",
"postcode":"4128",
"state_address":null,
"message":"",
"computed_price":"4102.00",
"quote_source":"Piranha Off Road website",
"follow_up":null,
"follow_up_date":null
}
},
{
"vehicle":{
"v_id":"4220",
"make":"Toyota",
"model":"Hilux",
"year":"2020",
"cab_type":"Single Cab",
"engine":"Petrol",
"vehicle_feature":"Reverse Camera ",
"fitting_location":"Brisbane, QLD 4014",
"quote_id":"PO3640"
}
},
{
"traycanops":{
"id":"3974",
"product":"Steel UTE Tray",
"installation":"Piranha Branch",
"tray_size":"2400L x 1825W x 260H",
"tray_color":"Black",
"tub_removal":"Please remove my tub as part of installation",
"drivetrain":"2WD",
"tail_lights":"Standard Globe Light",
"claim_tub":null,
"get_tray_floor":null,
"canopy_size":null,
"canopy_color":null,
"paint_color":null,
"paint_code":null,
"canopy_type":null,
"floor_type":null,
"window_type":null,
"deck_type":null,
"doors":null,
"jack_off_style":null,
"canopy_finish":null,
"bundle":"false",
"powdercoat":"No",
"powdercoat_ac":null,
"quote_id":"PO3640",
"base_price":"$4102.00"
}
},
{
"accessories":null
}
]
Here's what I have done:
I did var result = JSON.parse(data); then var customer = JSON.parse(JSON.stringify(result[0])); and it gives me this:
I tried:
var customerdata = [];
$.each(customer, function(arrkey, arritem) {
customerdata.push(customerdata[arrkey]=arritem);
});
console.log(customerdata);
but it gives me this:
I just want something like customer.c_id instead of using loop. is this possible?
Thanks to https://stackoverflow.com/users/9513184/iota and https://stackoverflow.com/users/7941251/superstormer , I solve this by:
var result = JSON.parse(data);
console.log(result[0].customer.c_id);
//result: 4047

How can I merge individual object values?

I have the following problem:
I want to read out my table names from a SQL database and then make a comparison as to whether it already exists. I know there is the formula IF EXISTS ... but IF doesn't work .. So here's my previous variant:
First i extracted everything before the filename.csv (C:\Users\Frederic\Desktop\Drag&Drop...) and then the ".csv". Do not be surprised why 51;) The filename is so long
var filename = filePath.slice(51);
var richtigername = filename.replace(".csv","").toString();
console.log(richtigername)
here the result in the console:
for example: fxbewertung
As a second step I let me show the file names:
connection.query('Show tables from datein', function(err, datein) {
let string = JSON.stringify(datein);
let json = JSON.parse(string);
console.log(json)
here the result in the console:
[ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
Furthermore, I extracted the values (name of the SQL tables):
for (var k = 0; k < json.length; k++) {
var werte = Object.values(json[k])
console.log(werte)
};
here the result in the console:
[ 'fxbewertung' ]
[ 'kontoauszug' ]
[ 'lsreport' ]
Now I don't know how i can take the comparison that for example for the file fxbewertung exist a database ('fxbewertung').
My consideration is to somehow browse the individual arrays .. or merge and then browse. At the end should come out true or false
P.S .: it may well be complicated yet but I'm not a real programmer or something;)
Best regards
Frederic
You can use some() method to check if a table exists for that filename.
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
Live Example:
var tables = [{
Tables_in_datein: 'fxbewertung'
},
{
Tables_in_datein: 'kontoauszug'
},
{
Tables_in_datein: 'lsreport'
}
];
var filename = 'fxbewertung';
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
if (!tableExists) {
// Table not found for filename.
} else {
// Table found. Do something.
}
Assuming you finished executing your query and stored the data as following:
const queryResult = [ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
You'll then need to map this array to extract the values and store them in a single array like so:
const values = queryResult.map(e=>e[Object.keys(e)[0]]) // ["fxbewertung", "kontoauszug", "lsreport"]
Since you're looking for a true/false result by giving a file name, you'll need to use indexOf to achieve that.
const valueExists = filename => values.indexOf(filename) !== -1
After that execute valueExists with the file name you're looking for:
valueExists("kontoauszug"); // true
valueExists("potato"); // false
Hope this helps!
An efficient solution could be to use Array.prototype.find(). Where it would return from the moment it finds a truthy value and would not iterate till the end (unless the match exists at the end).
Demo Code:
const tablesArr = [
{
Tables_in_datein: "fxbewertung"
},
{
Tables_in_datein: "kontoauszug"
},
{
Tables_in_datein: "lsreport"
}
];
const tabletoFind = "fxbewertung";
const tableFound = tablesArr.find(item => item["Tables_in_datein"] === tabletoFind) ? true: false;
console.log(tableFound);
if(tableFound){
//*yes table found*/
}else{
///*nope table not found*/
}

How to get values in Json Array and use each of them separately

I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);

Access JSON key value dynamically using jquery

Below is my json which is dynamic. I want to access 'bf' key in the json , 'xxxxxx20160929' and 'yyy813AI20160929' keys are dynamic but json structure will be the same
{
"resultData": [
{
"a": "124",
"b": "0",
"c": "0",
"flc_schedu": {
"e": "6",
"f": "en",
"xxxxxx20160929": [
{"ID": "yyyyyyyy" },
{"ID": "fffff"}
]
},
"fareDetails": {
"xxxxxx20160929": {
"yyy813AI20160929": {
"O": {
"AD": {
"bf": "2527"
}
}
}
}
}
}
]
}
Below is how I tried
response.resultData[0].fareDetails[Object.keys(response.resultData[0].fareDetails)[0]]
If I try as above I can able to access dynamically up to "xxxxxx20160929" key, but I can't able get how to reach up to "bf" key dynamicaly.
You can reference an object using the array syntax.
var one = 'xxxxxx20160929';
var two = 'yyy813AI20160929';
data.resultData[0].fareDetails[one][two].O.AD.bf;
UPDATE:
This code assumes there is only one dynamic object at each layer.
var one = Object.keys(data.resultData[0].fareDetails)[0];
var two = Object.keys(data.resultData[0].fareDetails[one])[0];
var thing = data.resultData[0].fareDetails[one][two].O.AD.bf;
function getBFFromFareDetails(details){
var bfValues = [];
for(var k in details.fareDetails){
// loop over the children of fareDetails
if( details.fareDetails.hasOwnProperty( k ) ) {
//each entry in ;fareDetails'
var itemRoot = details.fareDetails[k]
for(var k1 in itemRoot){
// loop over the children of the first unknown item
if( itemRoot.hasOwnProperty( k1 ) ) {
//return the bf from the first unknown child
return itemRoot[k1].O.AD.bf;
}
}
}
}
}
If you call this with var bf = getBFFromFareDetails(response.resultData[0])
this will return the value for the first bf in the first child of fareDetails and its first child.
You can see a quick example in action here https://jsfiddle.net/tocsoft/5364x2sp/
If you are able to access up to "xxxxxx20160929" level then create a var to store that level, then use that variable to access the next which you will need to store in a variable, then use both variable to access the key needed.
var1 = response.resultData[0].fareDetails)[0];
var2 = response.resultData[0].fareDetails)[0][var1];
response.resultData[0].fareDetails)[0][var1][var2];

how to increase custom count in jquery json

If laptop model and serial id are same, i've to add new field totalModel and increase count. For example in below case: serialid "1" and laptop model "xyz" are coming two time so i want to add "totalModel" count as 2 and so on. How can i achieve this in jquery
This question is not really about jQuery, it is about mapping and filtering arrays and objects. However, we can use some jQuery convenience methods to solve it.
A large part of solving these problems is by properly defining what you want to do. It sounds from your question that you want to get a map of unique serial ids per laptop model type. We can use JavaScript's Array.prototype.reduce to produce just such a map (Note that we will take the 'sold' value for the first of each laptop model we encounter):
var laptop_models = data.reduce(function (memo, obj) {
if (!memo[obj.laptopModel]) {
memo[obj.laptopModel] = {
unique_serial_ids: [],
sold: obj.sold
};
}
if ($.inArray(obj.serialid, memo[obj.laptopModel].unique_serial_ids) === -1) {
memo[obj.laptopModel].unique_serial_ids.push(obj.serialid);
}
return memo;
}, {});
Next, we can map our laptop_models object into the array you specified as your expected result:
var result = $.map(laptop_models, function (laptop_model, model_name) {
return {
laptopModel: model_name,
totalModel: laptop_model.unique_serial_ids.length,
sold: laptop_model.sold
};
});
You got the idea already. Iterate through the array.
if them item is in a hash, increment the count, otherwise, add to the hash and set the count to 1
var hash = {};
for (var i = 0;i<data.length;i++) {
if (hash[data[i].laptopModel) {
hash[data[i].laptopModel]++;
}
else
hash[data[i].laptopModel] = 1;
}
var data = [
{
"serialid": 1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 5
},
{
"serialid" :1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 4
},
{
"serialid": 1,
"laptopModel": "abc",
"sold": "yes",
"cnt": 3
},
{
"serialid": 3,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 2
}];
var result = []; //work if result = {};
var tempArray = []; // used to store unique name to prevent complex loop
data.forEach(function(item){
if($.inArray(item.laptopModel, tempArray)< 0){// unique name
result.push(formatData(item));
tempArray.push(item.laptopModel);
}
else{
var indexNew = $.inArray(item.laptopModel, tempArray);
result[indexNew]["totalModel"] += 1;
}
});
function formatData(item){
return{
"laptopModel": item.laptopModel,
"sold": item.sold,
"totalModel": 1
}
}
alert(JSON.stringify(result)); //expect array 2 item but it's empty array
console.log(result); //Will have result 2 item when I view console window
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources