Concatenate string with JSON [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 days ago.
The community is reviewing whether to reopen this question as of 9 days ago.
Improve this question
I have a requirement like I have two JSONs, in that I need to append some string. I tried that. I have send this to back-end with JSON.stringify. However, JSON stringify is adding extra double quotes and backslashes. How to avoid this?
At agents it is adding like this "agents":["{\"agent\":[{\"refURL\":\"/unifiedconfig/config/agent/5105\",\"agentId\":\"1304\",\"firstName\":\"Demetra\",\"lastName\":\"Moore\",\"userName\":\"cgmoore\"}]}"]}
var obj = {
"refURL": "/unifiedconfig/config/agentteam/5020",
"changeStamp": 18,
"agentCount": 0,
"description": "Cumulus All Team",
"name": "CumulusAll",
"peripheral": {"id": 5000, "name": "CUCM_PG_1"},
"peripheralId": 5000,
"supervisorCount": 0,
"agents": [{}]
};
var AgentXML = {
"refURL": "/unifiedconfig/config/agent/5105",
"agentId": "1304",
"firstName": "Demetra",
"lastName": "Moore",
"userName": "cgmoore"
};
AgentXML = '{"agent":[' + JSON.stringify(AgentXML) + ']}';
obj.agents = [AgentXML];
console.log(JSON.stringify(obj));
Actually final output should be like below
{
"refURL": "/unifiedconfig/config/agentteam/5016",
"changeStamp": 201,
"agentCount": 3,
"description": "Cumulus Finance Team",
"name": "CumulusFinance",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [
{
"agent": [
{
"refURL": "/unifiedconfig/config/agent/5101",
"agentId": "1300",
"firstName": "Sammy",
"lastName": "Jackson",
"userName": "cgjackson"
}
]
}
]
}

JSON is a serialisation format. Don't use it to manipulate data.
Let's go step by step. obj.agents is an array with a single element an empty object. Its path is:
obj.agents[0]
To add a new property to that object:
obj.agents[0].newPropertyHere = ...
To set that new property to an empty array:
obj.agents[0].newPropertyHere = [];
To append a value to the array:
obj.agents[0].newPropertyHere.push(...)
... but you can create the array and populate it at once:
obj.agents[0].newPropertyHere = [...];
All together:
var obj = {
"refURL": "/unifiedconfig/config/agentteam/5020",
"changeStamp": 18,
"agentCount": 0,
"description": "Cumulus All Team",
"name": "CumulusAll",
"peripheral": {"id": 5000, "name": "CUCM_PG_1"},
"peripheralId": 5000,
"supervisorCount": 0,
"agents": [{}]
};
var AgentXML = {
"refURL": "/unifiedconfig/config/agent/5105",
"agentId": "1304",
"firstName": "Demetra",
"lastName": "Moore",
"userName": "cgmoore"
};
obj.agents[0].agent = [AgentXML];
console.log(obj);
Final JSON conversion omitted for clarity.

Work with JavaScript objects and arrays, not with JSON. Serialize only once at the end:
const agent = {
refURL: "/unifiedconfig/config/agent/5105",
agentId: "1304",
firstName: "Demetra",
lastName: "Moore",
userName: "cgmoore"
};
const obj = {
refURL: "/unifiedconfig/config/agentteam/5020",
changeStamp: 18,
agentCount: 0,
description: "Cumulus All Team",
name: "CumulusAll",
peripheral: {id: 5000, name: "CUCM_PG_1"},
peripheralId: 5000,
supervisorCount: 0,
agents: [agent]
};
console.log(obj);
console.log(JSON.stringify(obj));
Removing the quotes improves the syntax highlighting in a stack snippet. Changing the order reduces complexity. I removed agent in AgentXML, because I assume it's not correct.
If you expect the property:
const agent = {
refURL: "/unifiedconfig/config/agent/5105",
agentId: "1304",
firstName: "Demetra",
lastName: "Moore",
userName: "cgmoore"
};
agent.agent = JSON.stringify(agent);
const obj = {
refURL: "/unifiedconfig/config/agentteam/5020",
changeStamp: 18,
agentCount: 0,
description: "Cumulus All Team",
name: "CumulusAll",
peripheral: {id: 5000, name: "CUCM_PG_1"},
peripheralId: 5000,
supervisorCount: 0,
agents: [agent]
};
console.log(obj);
console.log(JSON.stringify(obj));

Related

How to compare and manipulate json object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
I need to compare and manipulate JSON objects.
First object
let data1 = {
"id": "111",
"entity_id": "222",
"text_id": "333",
"details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving"
}]
}
Second object
let data2 = [{
"id": "111",
"text_id": "333",
"criteria_type": "TXT",
"value": 1000,
"comp": {
"id": "444",
"name": "driving"
}
}, {
"id": "222",
"text_id": "444",
"criteria_type": "TXT",
"value": 2000,
"comp": {
"id": "555",
"name": "swiming"
}
}]
There are 2 objects data1 and data2. Here, I need to compare the data1.details array with the data2 array key => data1.details.comp_id with data2.comp.id if not match then I need to push value, id and name to data1 object. Please help me to resolve this issue.
Resulting object
data1 will be:
{
"id": "111",
"entity_id": "222",
"text_id": "333",
"declaration_details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving",
}, {
"value": 2000,
"comp_id": "555",
"CompName": "swiming",
}]
}
Based on your expected result, wouldn't you just need to map data2 to the declaration_details of the resulting object?
const main = () => {
const { details, ...rest } = data1;
const result = {
...rest,
fbp_year: new Date().getUTCFullYear(),
declaration_details: data2.map(({
value,
comp: {
id: comp_id,
name: CompName
}
}) => ({
value,
comp_id,
CompName
}))
};
console.log(result);
};
const
data1 = {
"id": "111",
"entity_id": "222",
"text_id": "333",
"details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving"
}]
},
data2 = [{
"id": "111",
"text_id": "333",
"criteria_type": "TXT",
"value": 1000,
"comp": {
"id": "444",
"name": "driving"
}
}, {
"id": "222",
"text_id": "444",
"criteria_type": "TXT",
"value": 2000,
"comp": {
"id": "555",
"name": "swiming"
}
}];
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
Use filter() to find objects in the data2 matching comp.id. Then you can just use map() to create a new array. Finally, you can add the mappedData2 array to the data1 in declaration_details.
let filteredData2 = data2.filter(item => {
return data1.details.some(detail => detail.comp_id === item.comp.id);
});
let mapData = filteredData2.map(item => {
return {
value: item.value,
comp_id: item.comp.id,
CompName: item.comp.name
};
});
You can use JSON.stringify(yourJsonObject) to convert your objects to strings.
Then you can compare them like this. areEqual = string1 == string2. Make sure the object properties are in the same order for both objects.

Loop through array of object and get values

I have below object and i need counts from the byPerson array inside the object. Basically, i want to check the count in each byPerson array elements and get those properties as an array.
for e.g.
var Closed = [16, 0, 1, 43] // here 1st count object has 16 as closed, 2nd count object has no closed property (so we set it to 0), 3rd one has value 1 and 4th one has value 43
Similarly
var Verify = [0, 5, 0, 1]
How can i achieve this calculation and stored the results in Closed and Verify variables as shown above.
{
"byPerson": [
{
"personId": "1514903899",
"firstName": "Yatish",
"lastName": "Patel",
"count": {
"Closed": 16,
}
},
{
"personId": "1559363884",
"firstName": "Samuel",
"lastName": "Chacko",
"count": {
"Verify": 5
}
},
{
"personId": "297895805",
"firstName": "Tim",
"lastName": "Altman",
"count": {
"Closed": 1
}
},
{
"personId": "others",
"firstName": "Others",
"lastName": "",
"count": {
"Closed": 43,
"Verify": 1
}
}
],
"resultDateTime": "2021-04-23T12:14:33.901"
}
I tried this way
const closedValues= releaseData.byPerson.map(element => element.count["Closed"] === undefined ? 0: element.count["Closed"]);
const verifyValues= releaseData.byPerson.map(element => element.count["Verify"] === undefined ? 0: element.count["Verify"]);
```
But i guess it is not the optimal solution where i have to calculate for each one seperately.
You can use Array.reduce to count this in one go:
const data = {
"byPerson": [{
"personId": "1514903899",
"firstName": "Yatish",
"lastName": "Patel",
"count": {
"Closed": 16,
}
},
{
"personId": "1559363884",
"firstName": "Samuel",
"lastName": "Chacko",
"count": {
"Verify": 5
}
},
{
"personId": "297895805",
"firstName": "Tim",
"lastName": "Altman",
"count": {
"Closed": 1
}
},
{
"personId": "others",
"firstName": "Others",
"lastName": "",
"count": {
"Closed": 43,
"Verify": 1
}
}
],
"resultDateTime": "2021-04-23T12:14:33.901"
}
const result = data.byPerson.reduce((result, {
count
}) => {
result.closed.push(count.Closed || 0);
result.verify.push(count.Verify || 0);
return result;
}, {
closed: [],
verify: []
});
console.log(result);

I want to count number of times ID's are present in Json Response [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson#reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
},
{
"id": 8,
"email": "lindsay.ferguson#reqres.in",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
},
{
"id": 9,
"email": "tobias.funke#reqres.in",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"
},
{
"id": 10,
"email": "byron.fields#reqres.in",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
},
{
"id": 11,
"email": "george.edwards#reqres.in",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
},
{
"id": 12,
"email": "rachel.howell#reqres.in",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
}
]
}
above is the json response. It has field names"id, email, first_name, last_name and avatar". I need to validate the count of each of these field. Expected output is :id-6 , first-name-6, email-6, last_name-6 , avatar-6.And I do not want to hard code, these fields are present in one of the csv file. Means I do not want to hard code field name, I want to parametrize so that it reads data from csv file. So that even if I have to get the count of 100 fields, the code should work. Please let me know if any other details required
you can simply count it this way
console.log(value.data.length)
unless if there is any chance that there would have been no id field then u can do this
var count = 0;
for (let i =0; i < value.data.length; i++) {
if(value.data[i].id != undefined) count++
}
console.log(count)

Object not replacing using spread operator

I want to replace existing object with new updated fields using spread operator. But I am not getting the correct result.
Below are my two objects.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
I can do it with .map. Below is my code.
let result = obj1.map(item => {
if (item.id === newObj.id) {
return {...item, ...newObj};
}
return item;
});
But I do not want to run the loop and want to acheive by spread operator only.
Example for spread. Which is not working. It's not replacing the object. Instead creating one more.
[...obj1, newObj];
Can someone help me?
JSBIN CODE SNIPPET
Spread syntax doesn't replace the object within array like you used it. Using map is the simplest and understandable way. However if you want to use spread syntax you would first need to find the index to be replaced and then use slice on array
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
const idx = obj1.findIndex(item => item.id === newObj.id);
obj1 = [...obj1.slice(0, idx), newObj, ...obj1.slice(idx + 1)];
console.log(obj1);
Use Object.assign
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
Object.assign(obj1[2], newObj);
console.log(obj1)
Using .find() to get the target obj
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
const targetObj = obj1.find(obj => obj.id === newObj.id)
Object.assign(targetObj, newObj);
console.log(obj1)
you should normalize your data by id this way:
obj1 = {
1: {
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
2: {
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
3: {
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
}
newObj = {
3: {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
}
this way you can use spread operator:
{ ...obj1, ...newObj }
in order to normalize you can use the reduce func this way:
const normalized = obj1.reduce((result, obj) => ({ ...result, [obj.id]: obj }), {})
Spread operator is magic but it won't do whatever you want, you will have to loop over and replace the object. Instead of doing a map(), I would prefer find(). The use Object.assign() to achieve what you want.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
let foundOb = obj1.find(e => e.id === newObj.id);
Object.assign(foundOb, newObj)
console.log(obj1)
You cannot use spread syntax in that way. One solution would be to find index of the object you want to replace by id property and then you could use spread syntax with slice method to create new array with replaced object.
let obj1 = [{"id":1,"name":"Michel","age":34,"email":"michel#gmail.com"},{"id":2,"name":"Abby","age":40,"email":"abby#gmail.com"},{"id":3,"name":"Gary","age":40,"email":"abby#gmail.com"}]
let newObj = {"id":3,"name":"Gary","age":23,"email":"gary#gmail.com"}
const index = obj1.findIndex(({id}) => id == newObj.id)
const result = [...obj1.slice(0, index), newObj, ...obj1.slice(index + 1)]
console.log(result)
I would do something like:
updatedObj = [obj1.map((entry) => entry.id !== newObj.id), newObj]
This would give me the updated object with minimal syntax

How to define array of objects in side nested array mongoose [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 3 years ago.
I have an express API using an already populated mongoDB and have defined the schema like so:
const accountHolderSchema= new mongoose.Schema({
pid: {Type: Number},
accountNumber: {type: String},
relationshipType: {type: String},
firstName: {type: String},
middleName: {type: String},
lastName: {type: String}
});
const accountsSchema = new mongoose.Schema({
accountNumber: String,
accountType: String,
accountHolder: [accountHolderSchema]
});
const productDetailSchema = new mongoose.Schema({
pid: Number,
accounts: [accountsSchema]
});
I have literally copied and paste all the properties and from the database so i know they match so i know that's out of the picture
The RESPONSE I get is this:
{
"pid": 2697143,
"accounts": [
{
"accountHolders": [
{
"pid": 13209741,
"accountNumber": "403716000062",
"relationshipType": "BENEFICIARY",
"firstName": "Maria",
"middleName": "Delores",
"lastName": "Jackson"
}
]
"accountNumber": "12345",
"accountType": "RSA",
}
]
}
BUT what the response I WANT to get in return is this:
{
"pid": 2697143,
"accounts": [
{
"accountNumber": "12345",
"accountType": "RSA",
"accountHolders": [
{
"pid": 13209741,
"accountNumber": "403716000062",
"relationshipType": "BENEFICIARY",
"firstName": "Maria",
"middleName": "Delores",
"lastName": "Jackson"
}
]
}
]
}
I want the accountNumber and accountNumber to come before accountHolders field.
I'm not sure if its the way how i define a nested array inside of another nested array that's throwing of the structure. If I don't the define accountHolderSchema the structure is returned fine. Any ideas?
If the order of the propreties is really important to you, you could use some simple JavaScript.
Loop through your Schema propreties and assign the propreties to an obj.
(Object.keys(obj)) will return an array with the propreties, then you make an organized copy of your document by getting the keys from the array and assigning values from the document.
let schema = {
"pid": 2697143,
"accounts": [
{
"accountNumber": "12345",
"accountType": "RSA",
"accountHolders": [
{
"pid": 13209741,
"accountNumber": "403716000062",
"relationshipType": "BENEFICIARY",
"firstName": "Maria",
"middleName": "Delores",
"lastName": "Jackson"
}
]
}
]
}
let doc = {
"pid": 2697143,
"accounts": [
{
"accountHolders": [
{
"pid": 13209741,
"accountNumber": "403716000062",
"relationshipType": "BENEFICIARY",
"firstName": "Maria",
"middleName": "Delores",
"lastName": "Jackson"
}
],
"accountNumber": "12345",
"accountType": "RSA",
}
]
}
let docOrganized= {};
docOrganized.pid = doc.pid;
Object.keys(schema.accounts[0]).map(key => docOrganized[key] = doc.accounts[0][key]);
console.log(docOrganized);

Categories

Resources