Getting a variable from a multidimentional JSON array using Jquery - javascript

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig

response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.

Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});

Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

Find a key value based on a match in Javascript

I'm trying to return the uuid where the urns key has this match.
"urns": [
"whatsapp:27820111111"
],
What should be returned d7b9f88c-b359-4d69-926d-536c0d2892e0 since it has that phone number match. How can this be done programmatically.
Here's are the two dicts.
{
"next": "https://random.com=",
"previous": null,
"results": [
{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [
{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [
{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
]
}
I'm able to loop through and find the urn but I'm not sure how to step back to get the uuid.
Pass in the results array and the urn string to this function. If found it will return the uuid, else it will return null.
function getIdFromUrn(results, urn) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.urns.includes(urn)) {
return result.uuid; // urn found
}
}
return null; // not found
}
console.log(getIdFromUrn(results, 'whatsapp:27820111111'));
You don't need to loop when you can use find(...) to match against a value.
See demo below
var data = [{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
];
const lookingFor = "whatsapp:27820111111";
const foundIt = data.find(el => {
return (el.urns.indexOf(lookingFor) !== -1);
});
console.log(foundIt.uuid);

how to get particular key value from all the objects in a AJAX call

here is the code ,i just want to grab "url" key and its value and store it in a variable
i have tried several ways to segregate the key named url you can see that in my commented code
$.ajax({
type: 'GET',
url: "url",
// data: data,
// async: false,
beforeSend: function(xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(res) {
// console.log(res);
// re=JSON.stringify(res);
re = $.parseJSON(res)
console.log(re['url'])
// console.log(re)
// console.log(re["url"])
// for(var url in re) {
// var value = objects[key];
// }
// console.log(Object.values('url'));
// ok=Object.keys(re).map(key => re[url])
// console.log(ok)
// console.log(re)
// $.each(re, function(key, value){
// console.log(key + value);
// });
// console.log(re[url])
// const seg = re.find(item => item.key === "url");
// const result=seg
// console.log(result)
// alert(res);
}
});
You need to resolve CORS issues with your Django backend to get the response correctly.
I see the response is of the following structure:
{
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": null
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": null
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": null
},
...
]
}
To get the url you can simply use .map on the results array:
let response = {
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": "www.a.com"
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": "www.b.com"
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": "www.c.com"
}
]
}
console.log(response.results.map(item => {
return {
"url": item.url
}
}))

Find all occurrences of JSON element using jQuery

How can you parse out all the values for a particular data point within a complex json response form a rest service call?
Here is my JQUERY code to get the rest service json response. I am looking to get all occurrences of "Id" for all "Approver" elements found in the json data and add them to delimited list - preferably using a
;
to separate each "Id"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'MySite/Change/Request/12345/Approvals/GetApprovalGroupUsers?changeNumber=98765',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.Id
}));
});
}
});
});
});
</script>
</head>
<body>
<button>Click me to get listing of Id's</button>
</body>
</html>
The json data from the service in such:
{
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
This is how you can get all ID's of the approvers, delimited by a semi-colon.
var data = {
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
data.PossibleApprovers.forEach(function (approver) { document.write(approver.Approver.Id + ';')})

Need help in lodash combinations to get the below object

Below is my object First step is to check the socialAuth array of objects and get the platformName which has the showStats value as false.
I have accomplished the step1 as below
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {'showStats': false}), "platformName");
['Twitter'] is the output of the arrList2
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [
{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}
],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
Second step is to check the above arrList2 with the sociaStats array and remove the value from it and print the object again.
I need help in this second step.
I need the resulting object as
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
You need to use _.remove() to remove the elements from array based on your condition.
Demo
var creatorObj = {
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}],
"socialAuth": [{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
}, {
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}]
};
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {
'showStats': false
}), "platformName");
creatorObj.socialStats = _.remove(creatorObj.socialStats, function(n) {
return !_.includes(arrList2, n.platformName);
});
console.log(creatorObj);
document.write(JSON.stringify(creatorObj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Categories

Resources