Iterating an Object using .map to display the inner array values - javascript

I have a JSON stringified object as:
{
"lesseeName": "Padyster-7",
"lesseeRegNo": "12345",
"lesseeVatNo": "4456",
"telFaxNo": "1234567891",
"billingAddress": {
"addressId": null,
"addressLine1": "XYz , l1 street",
"addressLine2": "near xyz bank",
"postalCode": "60000",
"countryName": "MY",
"cityName": "Kuala lumpur",
"stateProvinceCode": "Kuala lumpur"
},
"mlaList": [{
"mlaNo": 92,
"lesseeId": 108,
"executionDate": "27/01/2017",
"signatoryInfo": "Test",
"overdueRate": 3.44,
"nonPaymentDays": 2,
"consolidationTerm": "Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "tooot#gmail.com",
"leaseMlaNo": "OPM1",
"statusDescription": "APPROVED"
}, {
"mlaNo": 93,
"lesseeId": 108,
"executionDate": "03/01/2017",
"signatoryInfo": "tess",
"overdueRate": 5.77,
"nonPaymentDays": 2,
"consolidationTerm": "Bi-Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "xyz#gmail.com",
"leaseMlaNo": "OPM2",
"statusDescription": "APPROVED"
}]
}
I am working in Reactjs and I want my object to be iterated such that the inner array mlaList of objects gets iterated to display value one after other.
whenever I try using the .map function to the parent object I get an error saying ".map is not a function" below is the iteration I attempt which fails:
{data.map((data, index) => {data.leaseMlaNo} {data.signatoryEmail})}
I have referred to the SO questions quite similar to this one, but they just talk about iterating the objects using Object.keys
Please help me understand what I am doing wrong and what should be the correct way to achieve this

The method Array#map is a method of the Array class, and not of the Object class. However, the mlaList property is an array, and you can iterate it. You should use data.mlaList.map():
// if the data is stringified - const data = JSON.parse({ the object });
const data = {"lesseeName":"Padyster-7","lesseeRegNo":"12345","lesseeVatNo":"4456","telFaxNo":"1234567891","billingAddress":{"addressId":null,"addressLine1":"XYz , l1 street","addressLine2":"near xyz bank","postalCode":"60000","countryName":"MY","cityName":"Kuala lumpur","stateProvinceCode":"Kuala lumpur"},"mlaList":[{"mlaNo":92,"lesseeId":108,"executionDate":"27/01/2017","signatoryInfo":"Test","overdueRate":3.44,"nonPaymentDays":2,"consolidationTerm":"Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"tooot#gmail.com","leaseMlaNo":"OPM1","statusDescription":"APPROVED"},{"mlaNo":93,"lesseeId":108,"executionDate":"03/01/2017","signatoryInfo":"tess","overdueRate":5.77,"nonPaymentDays":2,"consolidationTerm":"Bi-Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"xyz#gmail.com","leaseMlaNo":"OPM2","statusDescription":"APPROVED"}]};
const result = data.mlaList.map((o, index) => o.signatoryEmail); // in react <div key={index}>{o.signatoryEmail}</div> for example
console.log(result);

array.prototype.map is an array function, not for objects so you would want to call it on your mlalist key:
const data = {"lesseeName":"Padyster-7","lesseeRegNo":"12345","lesseeVatNo":"4456","telFaxNo":"1234567891","billingAddress":{"addressId":null,"addressLine1":"XYz , l1 street","addressLine2":"near xyz bank","postalCode":"60000","countryName":"MY","cityName":"Kuala lumpur","stateProvinceCode":"Kuala lumpur"},"mlaList":[{"mlaNo":92,"lesseeId":108,"executionDate":"27/01/2017","signatoryInfo":"Test","overdueRate":3.44,"nonPaymentDays":2,"consolidationTerm":"Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"tooot#gmail.com","leaseMlaNo":"OPM1","statusDescription":"APPROVED"},{"mlaNo":93,"lesseeId":108,"executionDate":"03/01/2017","signatoryInfo":"tess","overdueRate":5.77,"nonPaymentDays":2,"consolidationTerm":"Bi-Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"xyz#gmail.com","leaseMlaNo":"OPM2","statusDescription":"APPROVED"}]};
const list = data.mlaList.map(val => `${val.leaseMlaNo} ${val.signatoryEmail}`);
console.log(list)

Related

map a 3 nested array javascript

const aboutMe = [{
"name": "frank",
"about": [{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": []
}
]
}]
const AllBreak = aboutMe.about.map((dinner) => ((dinner.first, dinner.last)));
const expectedOutput =["first": "desert", "last": "noodles", "first": "desert", "last": "noodles"]
console.log(aboutMe, AllBreak, expectedOutput)
so am trying to filter through a nested array learning from a tutorial I don't know why it returns cannot read property of map why is that pretty sure i filtered correctly according to the tutorial
Firstly, aboutMe is an array with an object that has an about property in it. So, if you want to access this property, you need to first access the first element of the array and then access the about property in it.
Secondly, (dinner.first, dinner.second) doesn't actually make any sense here.
Because when you have multiple expressions separated by commas in a bracket, each of those expressions get evaluated but only the last one is returned. So, here returning (dinner.first, dinner.second) is equivalent to returning dinner.second.
So, if you only want dinner.second then just return that or put them in an array (or object) and return that.
Also, since in your example it seems that it is not guaranteed that the dinner array would always have an object inside it, it is best to use Optional Chaining here.
Please have look at the solution below:
const
aboutMe = [{name:"frank",about:[{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[]}]}],
res = aboutMe[0].about.map(({dinner}) => [dinner?.[0]?.first, dinner?.[0]?.last])
console.log(res);
aboutMe is an array, if you want to get the property of the first element, you can use indexing [0]
const AllBreak = aboutMe[0].about.map(() => ...);

how to push array of objects inside an object to an array with unique index js

Question Explained:
I am doing a "for Each" loop to iterate key values and appending it with the api to get the response which is a single object. This object has a field called "issuselinks" which is a array of objects. My problem here is.. instead of storing the response object in an array i want to store the objects inside the "issueLinks" array into an array with separate index of each obj (i.e) issulinks[0] vaalue should sit in array[0] without looping the issuelinks. Thus my new array should contain objects of "issuselinks" instead of the whole response object. And I dont want to loop "issueLinks" and store it in a array since i already have more looping logic inside and which might go async. And if possible please tell me how to avoid loops.. which is going async. Thanks in advance!!
Here is my sample JSON Object:
{
"fields": {
"issuelinks": [
{
"id": "378753"
},
{
"id": "378752"
}
],
"assignee": null,
"customfield_10600": "9223372036854775807",
"customfield_12109": null,
"aggregatetimeestimate": null,
"comment": {
"comments": [],
"maxResults": 0,
"total": 0,
"startAt": 0
}
},
"customfield_10290": null,
"customfield_10291": null,
"customfield_10171": null,
"customfield_10053": "Req 21",
"customfield_10450": null,
"customfield_10451": null,
"customfield_10332": null,
"customfield_10453": null,
"customfield_11300": null,
"customfield_10455": null,
"customfield_12107": null,
}

combining javascript object property value and display

Hi I am having difficulty in traversing in javascript object. How can I get scheme_name & NAV from both and store it in variable like "You have 2 schemes linked to your account. scheme_name1 NAV value is "" scheme_name2 NAV value is "" and so forth. Please explain it to me thanx
let data = [{
"CustomerID": 12345,
"NAV": "95.24059718",
"cost_of_purchase": 799900,
"folio_number": 10007060,
"id": 1,
"mutual_fund_house": "AXIS MUTUAL FUND",
"no_of_units": 15000,
"option": "GROWTH",
"plan": "REGULAR",
"resource_uri": "/api/v1/folio/1/",
"scheme_name": "AXIS LONG TERM EQUITY",
"value_of_units": "1428608.9580"
}, {
"CustomerID": 12345,
"NAV": "1053.31517400",
"cost_of_purchase": 1500000,
"folio_number": 5540000567,
"id": 2,
"mutual_fund_house": "SBI Mutual Fund",
"no_of_units": 2750,
"option": "DIVIDEND",
"plan": "DIRECT",
"resource_uri": "/api/v1/folio/2/",
"scheme_name": "SBI Magnum Multicap Fund",
"value_of_units": "2896616.7270"
}]
It looks like you try to map that object to another object.
First, try to read and understand array methods, you can check:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
And for map method you can check:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
And as a specific answer you can do:
const mappedData = data.map(function(item) {
return {
scheme_name: item.scheme_name,
NAV: item.NAV
};
});
This will return you an array of a simplified version of yours.
After that, you can convert it to a string like:
let solution = `You have ${mappedData.length} schemes linked to your account. `;
mappedData.forEach(function(mapped) {
solution += mapped.scheme_name + ' is ' + mapped.NAV + ' '
});
Note: I showed map method for giving an insight about what you can do, normally you don't need to simplify, you can directly use for each version.
Imagine each one of your objects (in this case you have provided two (2)) as an associative array inside of an array. Meaning that rather than reference it by it's index position, you can reference it by it's key.
This means to access object 1, you would have to write data[0]. But if you alerted this, this would simply tell you that data[0] is an object. Which is is.
To access an actual value in that array, you would then have to provide the key, which you can do by providing a number, or in your case perhaps more easily, it's associated key, which is "scheme_name".
See the following :
let data = [{
"CustomerID": 12345,
"NAV": "95.24059718",
"cost_of_purchase": 799900,
"folio_number": 10007060,
"id": 1,
"mutual_fund_house": "AXIS MUTUAL FUND",
"no_of_units": 15000,
"option": "GROWTH",
"plan": "REGULAR",
"resource_uri": "/api/v1/folio/1/",
"scheme_name": "AXIS LONG TERM EQUITY",
"value_of_units": "1428608.9580"
}, {
"CustomerID": 12345,
"NAV": "1053.31517400",
"cost_of_purchase": 1500000,
"folio_number": 5540000567,
"id": 2,
"mutual_fund_house": "SBI Mutual Fund",
"no_of_units": 2750,
"option": "DIVIDEND",
"plan": "DIRECT",
"resource_uri": "/api/v1/folio/2/",
"scheme_name": "SBI Magnum Multicap Fund",
"value_of_units": "2896616.7270"
}]
for (let i = 0; i < data.length; i++) {
alert(data[i]["scheme_name"]);
}
So quite simply, for i = 0, with i being less than the number of associative arrays in your array named data, alert the value on that indexed array, by the associated key.
You've got an array of data so firstly you need to iterate through that array.
Pick which properties you want to keep per record, and save them to a results array.
Once you have the results you can iterate through them and print out your individual records.
let data = [{"CustomerID":12345,"NAV":"95.24059718","cost_of_purchase":799900,"folio_number":10007060,"id":1,"mutual_fund_house":"AXIS MUTUAL FUND","no_of_units":15000,"option":"GROWTH","plan":"REGULAR","resource_uri":"/api/v1/folio/1/","scheme_name":"AXIS LONG TERM EQUITY","value_of_units":"1428608.9580"},{"CustomerID":12345,"NAV":"1053.31517400","cost_of_purchase":1500000,"folio_number":5540000567,"id":2,"mutual_fund_house":"SBI Mutual Fund","no_of_units":2750,"option":"DIVIDEND","plan":"DIRECT","resource_uri":"/api/v1/folio/2/","scheme_name":"SBI Magnum Multicap Fund","value_of_units":"2896616.7270"}]
let results = []
data.forEach(datum => {
results.push({
scheme_name: datum.scheme_name,
nav: datum.NAV,
})
})
console.log(`You've got ${results.length} items in your account.`)
results.forEach(result => {
console.log(`${result.scheme_name} - NAV value is: ${result.nav}`)
})
I created sample fiddle for you. You need to iterate over each object in your main object and store all information outside.
data.forEach(function(item) {
console.log(item.scheme_name);
});

How to get specific data from object array?

I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});

tried to access value in object using the incorrect way

Edit
I tried to access value in object using the incorrect way, I have edited this question to stop others from making the same mistake.
Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test
<pre>
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
<pre>
what you have here is a object literal, witch can be manipulated without the use of jquery, to read this object you use the dot notation to get the object value based on the key
obj.key = value
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
var abc_status = obj.abc_status;//save the value to a variable
You're trying to access your json object as if it's an array. It's not. You can access your objects already since it's already a proper javascript object (it's not json). Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test.
Use underscore(_.pluck) get the specific values from the object.
Or try to define a new variable and reassign it .
var s = {
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null,
}
var t = {};
t['location'] = s.location;
t['status'] = s.status;
t['abc_status'] = s.abc_status;
t['s_s'] = s.s_s;
t['s_e'] = s.s_e;
t['n_c'] = s.n_c;
in case multiple arrays use underscore.

Categories

Resources