Add key values dynamically to nested object in Javascript - javascript

This might be a duplicate of this but did not get proper solution over there. I have object as below,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
]
}
}
}
}
}
I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,
"cc": {
"address": [
ccEmailId
]
}
So it will look like,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
],
"cc": {
"address": [
ccEmailId
]
}
}
}
}
}
}
I tried to add this using object[key] as below, object.key but no luck
replyDataObj[payload][emailAddresses][cc]={
"address": [
ccEmailId
]
}
I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.

Put strings inside []:
replyDataObj['payload']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}

As answered by #K.Kirsz, I was missing strings inside [] (quotes). Also added missing 'email' key to solve my issue.
replyDataObj['payload']['email']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}

Related

Getting second level nested object inside array of objects mongodb

My database looks like this:
[
{
"title": "man",
"articlesType": [
{
"title": "shoes",
"articles": [
{
"title": "shoes1",
"id": "randomId"
},
{
"title": "shoes2",
"id": "alsoRandomId"
}
]
}
]
},
{
"title": "woman",
"articlesType": [
{
"title": "pants",
"articles": [
{
"title": "pants1",
"id": "anotherRandomId"
},
{
"title": "pants1",
"id": "justId"
}
]
}
]
}
]
I expect something like this: , is it possible to get whole object in this nested just using an ID?
{
"title": "shoes2",
"id": "alsoRandomId"
}
I found this, but does not work for me
You can try an aggregation pipeline using double $unwind to deconstruct the array twice and then filter by your desired id (I'm assuming you want to match by the id).
And the last step, $project is to output the result in the same way as you want.
db.collection.aggregate([
{
"$unwind": "$articlesType"
},
{
"$unwind": "$articlesType.articles"
},
{
"$match": {
"articlesType.articles.id": "alsoRandomId"
}
},
{
"$project": {
"title": "$articlesType.articles.title",
"id": "$articlesType.articles.id"
}
}
])
Example here

How do you delete an empty array from javascript?

For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}

How can I get to the last level of a json nest and format the output dynamically?

I have this json:
[
{
"name": "MARVEL",
"superheroes": "yes"
},
{
"name": "Big Bang Theroy",
"superheroes": "NO",
"children": [
{
"name": "Sheldon",
"superheroes": "NO"
}
]
},
{
"name": "dragon ball",
"superheroes": "YES",
"children": [
{
"name": "goku",
"superheroes": "yes",
"children": [
{
"name": "gohan",
"superheroes": "YES"
}
]
}
]
}
]
I know how to loop and go through it but I need an output like this:
[
{
"name": "MARVEL",
"answer": [
{
"there_are_superheroes": "YES"
}
]
},
{
"name": "Big Bang Theroy",
"answer": [
{
"there_are_superheroes": "NO",
"new_leaft": [
{
"name": "sheldon",
"there_are_superheroes": "NO"
}
]
}
]
},
{
"name": "dragon ball",
"answer": [
{
"there_are_superheroes": "YES",
"new_leaft": [
{
"name": "goku",
"answer": [
{
"there_are_superheroes": "YES",
"new_leaft": [
{
"name": "gohan",
"answer": [
{
"there_are_superheroes": "YES"
}
]
}
]
}
]
}
]
}
]
}
]
I tried something like this:
format(d) {
if (d.children) {
d.children.forEach((d) => {
format;
});
}
}
format(data);
I don't know how to get the structure I want. I have tried to do it with foreach, but at one point I don't know how to dynamically access until the last children, this is an example but I can have n levels where there can be elements with more children. In my real project I am getting a structure from a web service, I need to structure it like this.
the attribute called superheroes I want it to be shown inside an array called answer and inside of it, there_are_superheroes it will have its value.
"name": "MARVEL",
"answer": [
{
"there_are_superheroes": "YES", --> `there_are_superheroes` was `superheroes`,
"new_leaft": [
{
.
.
and new_leaft is the equivalent of children
As I said, I know how to go through objects and arrays but in this case, I don't know how to go to the last children nested of each object.
This is how to do one level of recursion:
function format(l){
const result = {name: l.name};
result.answer = [{there_are_superheroes: l.superheroes}];
result.answer[0].new_leaft = l.children;
return result;
}
format({
"name": "Big Bang Theroy",
"superheroes": "NO",
"children": [
{
"name": "Sheldon",
"superheroes": "NO"
}
]
})
// result:
{
"name": "Big Bang Theroy",
"answer": [
{
"there_are_superheroes": "NO",
"new_leaft": [
{
"name": "Sheldon",
"superheroes": "NO"
}
]
}
]
}
If the list of possible keys is fixed, it's very simple. Otherwise use Object.assign to copy all the keys (or just iterate through those), then modify the necessary keys.
Now you have to figure out where to put the recursion calls (hint: l.children.map(format), whether the key should be named tree or new_leaf(t), check if the field exists and handle accordingly, (See the question In Javascript. how can I tell if a field exists inside an object? - Stack Overflow), etc.

Filtering subarray of objects

I need to filter a subarray of elements.
var university = {
"fax": "123345",
"email": "test#test.com",
"url": "www.test.com",
"classes": [
{
"number": "1",
"name": "maths",
"students": [
{
"name": "Max",
"exams": [
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
}
]
},
{...}
]
},
{...}
]
}
Ok I need to get all the classes without filtering, all the students of each class without filtering, but in the exams array I only need to get the ones that passed.
I tried the following:
university.classes.students.exams.filter(function (el) {
return el.passed
});
But it is not working...
I've googled a solution to this without success...any help would be appreciated.
classes and students are arrays - so you have to loop those as well:
university.classes.forEach(function(uniClass) {
uniClass.students.forEach(function(student) {
student.exams = student.exams.filter(function (el) {
return el.passed;
});
});
});

What is wrong with this JSON file?

I put it in a parser and all it gives me is "expecting string on line 19". I have no idea what that means.
{
"name": "Rajeev",
"children": [
{
"name": "Joe",
"children": [
{
"name": "Kevin",
"children": [
{
"name": "George"
}
]
},
{
"name": "John",
"children": [
{
"name": "Barb",
}{
"name": "Michael",
}{
"name": "Charles"
}
]{
"name": "Ravinder"
]
},
Your commas are in the wrong place, e.g.
"children": [
{
"name": "Barb"
},{
"name": "Michael"
},{
"name": "Charles"
}
]
The left one is the right one. see for yourself. you had many extra , and unclosed { and [
http://i.stack.imgur.com/9yKNN.jpg
You have a property / value:
"name": "Barb",
… with a trailing comma so the next thing must be another property / value (the string mentioned in the error message is the property name).
However you have:
}{
Either remove the comma or add more details about Barb.
Then you will need to put a comma between the two objects:
}, {
It seems likely that you intended to place the comma causing teh error between the two objects, so you can just move them.
(You have similar errors throughout the rest of the file)
Sorry for the first answer, I saw a missing comma and automatically assumed that was it, but there were many other errors in there. I think this is what you're trying to do
[
{
"name": "Rajeev",
"children": [
{
"name": "Joe",
"children": [
{
"name": "Kevin",
"children": [
{
"name": "George"
}
]
},
{
"name": "John",
"children": [
{
"name": "Barb"
},
{
"name": "Michael"
},
{
"name": "Charles"
}
]
}
]
}
]
},
{
"name": "Ravinder"
}
]

Categories