How to get value from a nested array by index in javascript? - 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

Related

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);

How to return one array from firebase-database list of data

I am working with firebase and javascript. I am trying to return one array from firebase-database after executing a query from two tables. When I console.log my data I get a separate array and object for each bit of data.
var userId = 'hirerId';
var chatIdRef = firebase.database().ref("members");
var chatsRef = firebase.database().ref("chats");
chatIdRef.child(userId).on('child_added', snap => {
chatsRef.child(snap.key).once('value', snap => {
items = [];
items.push({
text: snap.val().text,
chatId: snap.key
});
console.log(items);
});
});
This logs two separate arrays and objects: [{"text":"How are you","chatId":"chatId"}] [{"text":"Hi friend","chatId":"chatId2"}]
My desired result is [{"text": "How are you","chatId":"chatId"}, {"text":"Hi friend","chatId":"chatId2"}]
This is my data structure:
data structure
How can I achieve my desired result? Thanks
just use apply.push to join as many arrays as you want. However, you might want to move your items = []; array outside the function. That's what is causing your problem. You are emptying the array every time you push/function fires.
var ar1 = [{
"text": "How are you",
"chatId": "chatId"
}];
var ar2 = [{
"text": "Hi friend",
"chatId": "chatId2"
}];
ar1.push.apply(ar1, ar2);
console.log(ar1);

Javascript array parsing

var usersRows = [];
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
rows.forEach(function(row) {
usersRows.push(row);
});
console.log(usersRows);
}
else {
console.log('Error while performing Query.' + err);
}
});
It returned to me:
var usersRows = [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ];
I need to parse this and remove rowdatapacket; I need result like this:
userRows = { id: 1, name: 'my name is', number: '+999999\r\n' };
If you need to get rid of RowDataPacket's array and save it in yours you can also use this:
usersRows = JSON.parse(JSON.stringify(results));
Have you tried
userRows = RowDataPacket;
You might want to try JSON.stringify(rows)
Was unable to understand and implement the accepted the answer.
Hence, tried the long way out according the results I was getting.
Am using "mysql": "2.13.0" and saw that the this library returned array of array out of which:
Index 0 had array of RowDataPackets
Index 1 had other mysql related information.
Please find the code below:
var userDataList = [];
//Get only the rowdatapackets array which is at position 0
var usersRows = data[0];
//Loop around the data and parse as required
for (var i = 0; i < usersRows.length; i++) {
var userData = {};
//Parse the data if required else just
userData.name = userRows.firstName + userRows.lastName;
userDataList.push(userData);
}
If no parsing is required and you just want the data as is, you could use the solution like mentioned in link How do I loop through or enumerate a JavaScript object?
Have not tried it but could be tweaked and worked out.
There should be simpler way to do it but as a novice I found the above way server the purpose. Do comment in case of better solution.
RowDataPacket is the class name of the object that contains the fields.
The console.log() result [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ] should be read as "an array of one item, containing and array of one item, containing an object of class RowDataPacket with fields id, name, and number"

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>

js each loop add one more depth to an object or array

I have this array of pages urls, now i need to make a hierarchy of out it.
So from this:
allPages = [
{ "url": "/polygon/color/red.html", "name": "Red" },
{ "url": "/polygon/color/blue.html", "name": "Blue" },
{ "url": "/polygon/shape/tri.html", "name": "Triangle" },
{ "url": "/weight/heavy.html", "name": "Heavy Item" }
];
To this:
siteMap = [
polygon:
color:
[{url:"red.html", name:"Red"}],
[{url:"blue.html", name:"Blue"}],
shape:
[{url:"tri.html", name:"Triangle"}],
weight:
[{url:"heavy.html", name:"Heavy Item"}],
];
The final structure can be object or array. But i can only use JS, not jQuery nor php.
EDIT: Changed Input data into array of objects. Sorry for making this harder.
Fiddle: https://jsfiddle.net/ss92kw4a/2/
several steps:
First we split the strings into arrays:
for(i in all){
all[i] = all[i].substring(1).split("/");
}
Next we do a recursive insertion:
function insert(o, a){
if(a.length == 0){return; }
if(!o[a[0]]){
o[a[0]] = {};
}
insert(o[a[0]], a.slice(1));
}
We start the recursion like this:
ans = {};
all.forEach(function(entry){
insert(ans, entry);
});
All done. The result tree is now in the ans object:
console.log(ans);
UPDATE: this code makes the last level an array: https://jsfiddle.net/ss92kw4a/3/
You may use something like this:
var allPages = [
"/polygon/color/red.html",
"/polygon/color/green.html",
"/polygon/color/blue.html",
"/polygon/shape/tri.html",
"/polygon/shape/rect.html",
"/weight/heavy.html",
"/weight/light.html"
];
var siteMap = {};
for (var i in allPages) {
var fragments = allPages[i].match(/[^\/]+/g);
if (!!fragments) {
var currentMember = siteMap;
for (var j in fragments) {
fragment = fragments[j];
if(!currentMember.hasOwnProperty(fragment)) {
currentMember[fragment] = {};
}
currentMember = currentMember[fragment];
}
}
}
Might be enhanced, notably in the fact that ending leaves are objects,
but it works.

Categories

Resources