how to push new element to array of objects? [duplicate] - javascript

This question already has answers here:
Copy array items into another array
(19 answers)
Closed 10 days ago.
Here i have Array of objects, in this agents array has 0 elements. i have add an object to this. "agents": [{}] in this i want to add below element:
{
"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": [
{}
]
}
I want to add below element to the above in agents array "agents" [{}]
{
"agent": [
{
"refURL": "/unifiedconfig/config/agent/5101",
"agentId": "1300",
"firstName": "Sammy",
"lastName": "Jackson",
"userName": "cgjackson"
},
{
"refURL": "/unifiedconfig/config/agent/5106",
"agentId": "1305",
"firstName": "Angel",
"lastName": "Jolie",
"userName": "cgjolie"
},
{
"refURL": "/unifiedconfig/config/agent/5109",
"agentId": "1308",
"firstName": "Steve",
"lastName": "O",
"userName": "cgsteveo"
}
]
}
This is the final output i want to be achieved
{
"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"
},
{
"refURL": "/unifiedconfig/config/agent/5106",
"agentId": "1305",
"firstName": "Angel",
"lastName": "Jolie",
"userName": "cgjolie"
},
{
"refURL": "/unifiedconfig/config/agent/5109",
"agentId": "1308",
"firstName": "Steve",
"lastName": "O",
"userName": "cgsteveo"
}
]
}
],
"supervisors": [
{
"supervisor": [
{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}
]
}
]
}

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":[{}]}
const obj1= {
"agent":[{"refURL":"/unifiedconfig/config/agent/5101","agentId":"1300","firstName":"Sammy","lastName":"Jackson","userName":"cgjackson"},{"refURL":"/unifiedconfig/config/agent/5106","agentId":"1305","firstName":"Angel","lastName":"Jolie","userName":"cgjolie"},{"refURL":"/unifiedconfig/config/agent/5109","agentId":"1308","firstName":"Steve","lastName":"O","userName":"cgsteveo"}]
}
obj.agents.splice(0,1,obj1);
console.log(JSON.stringify(obj))
I replaced answer again, please check.
> Blockquote

You can either do it via expression or side-effect. I'm going to name your object oldObject and your agents object agentsObject.
Expression:
const newObject = {
...oldObject,
agents: [ agentsObject ],
};
Side-effect:
oldObject.agents = [ agentsObject ];

Related

how to add another element to json

I have a json like this
{
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
To the above json, i need to add another agent inside of agents[] of agents[], below is the element that i need to add
{"refURL":"/unifiedconfig/config/agent/2255","agentId":"1478","firstName":"kkk","lastName":"ddd","userName":"dddd"}
supposong you're dealing with a json object :
in that case , all you have is just to acess the correct json path then push the new json agent into the array of agents .
here the it should be like yourJsobObject.agents[0].agent
to insert New json just use push : yourJsobObject.agents[0].agent.push(newJsonAgent);
you can check below snippet as an example :
let json = {
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
let newAgent = {"refURL":"/unifiedconfig/config/agent/2255","agentId":"1478","firstName":"kkk","lastName":"ddd","userName":"dddd"}
json.agents[0].agent.push(newAgent);
console.log(json.agents[0].agent)

How to delete all properties of a type JSON [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 1 year ago.
I have the following object in my code.
[
{
"Name": "John Johnsson",
"Adress": "Linkoping",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Adress": "Norrköping",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Adress": "Stockholm",
"Role": "CTO"
}
]
How do I best delete all the "Adress" fields? So I end up with the following result. I've been struggling to find an answer to this basic question.
[
{
"Name": "John Johnsson",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Role": "CTO"
}
]
JavaScript has delete operator:
data.forEach(item => {
delete item['Address'];
})
You can read more about delete operator here.
You can do it like that: so you don't mutate the initial array.
const listWithoutAddress = list.map(({Adress, ...rest}) => ({...rest}));
To remove a property from a js object you can use the delete command, like this:
let arr = [
{
"Name": "John Johnsson",
"Address": "Linkoping",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Address": "Norrköping",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Address": "Stockholm",
"Role": "CTO"
}
];
console.log(arr);
arr.forEach(_=>{delete _.Address}); // <-- this is it
console.log(arr);

Trying to filters an array of objects by an array of numbers with find my index and forEach doesnt work

Im trying to filter all the contact I have with an array of numbers I want to remove. This should loop on every contact and remove the numbers not needed. Some contacts have two numbers and only one could be deleted but not the hole contact. I tried already to filter and see if the selected number is in an index but the forEach doesn't seem to be working any advice?. I don't think forEach returns something
const filteredContacts = contacts.filter(contact => numbers.indexOf(contact.phoneNumbers.forEach(phone => phone.number)) > -1);
//2 sample of all contacts
// contacts
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
//numbers not to have
numbers = [
5557664823,
1344043005,
5467865467,
]
//Expected
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
If I understood right, you want to filter out some numbers from the contact's phone numbers. One solution to this can be approached using Array.map() over the contacts array and replace the phoneNumbers array with a new filtered array. For the filtering procedure we can use Array.filter() and Array.includes() to check if a phone number belong to the list of numbers you want to filter out.
const contacts = [
{
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": [
{
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
{
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
{
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": [
{
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
];
// Numbers to filter out.
const numsToFilterOut = [5557664823];
let res = contacts.map(contact =>
{
contact.phoneNumbers = contact.phoneNumbers.filter(
// Unary plus is used to coerces (cast) the string to number.
phone => !numsToFilterOut.includes(+phone.digits)
);
return contact;
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

How to exchange the format of arrays? - javascript

This is my json data:
{
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
My Expected output:
{
"rows": [
{
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
"staffs": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
}
]
},
]
}
I want to exchange the first object into one array as staff, i dont know what kind of library or method is to make this stuff,
Like this? You can use ES 2018 Object spread to pull the properties you want into an object literal.
let a = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
let b = { "rows": [{ ...a.rows[0].login, "staffs": [ { ...a.rows[0] } ] } ] }
delete(b.rows[0].staffs[0].login)
console.log(b)
There are multiple ways to solve this problem. With simple javascript you can do it like this.
var data = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
var exchangedData = data["rows"].map((row) => {
row["id"] = row["login"]["id"]
row["username"] = row["login"]["username"]
row["firstName"] = row["login"]["firstName"]
row["lastName"] = row["login"]["lastName"]
row["code"] = row["login"]["code"]
row["staffs"] = [{ id: row["id"], code: row["code"], position: row["position"], salary: row["salary"]}]
delete row["login"]
delete row["position"]
delete row["salary"]
return row;
})
console.log(exchangedData)
var rows = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
};
var data = {rows:[]}
rows.rows.forEach(function(value, index){
data.rows.push(
_.assign(
{},
{
"id": value.login.id,
"username": value.login.username,
"firstName": value.login.firstName,
"lastName": value.login.lastName,
"code": value.login.code,
},{"staffs":[{"id":value.id, "code":value.code, "position": value.position, "salary": value.salary}]})
)});
console.log(data);
I think this is a much simpler solution that handles any number of objects in your rows array.
result = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
const data = result.rows.map(d => {
const {id, code, position, salary} = d
return Object.assign(d.login, {staffs: {...{id, code, position, salary}}})
})
console.log(data)

How can I access specific value of JSON object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I can't seem to console.log the item name and just that. It's in the position data -> pricing -> tables -> items -> name. I am going for an output that says "Toy Panda".
[
{
"event": "recipient_completed",
"data": {
"id": "msFYActMfJHqNTKH8YSvF1",
"name": "Sample Document",
"status": "document.draft",
"date_created": "2014-10-06T08:42:13.836022Z",
"date_modified": "2016-03-04T02:21:13.963750Z",
"action_date": "2016-09-02T22:26:52.227554",
"action_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed"
},
"created_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"recipients": [
{
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "signer",
"recipient_type": "Signer",
"has_completed": true
}
],
"sent_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"metadata": {
"salesforce_opp_id": "123456",
"my_favorite_pet": "Panda"
},
"tokens": [
{
"name": "Favorite Animal",
"value": "Panda"
}
],
"fields": [
{
"uuid": "YcLBNUKcx45UFxAK3NjLIH",
"name": "Textfield",
"title": "Favorite Animal",
"value": "Panda",
"assigned_to": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "Signer",
"recipient_type": "signer",
"has_completed": true,
"type": "recipient"
}
}
],
"pricing": {
"tables": [
{
"id": 82307036,
"name": "PricingTable1",
"is_included_in_total": true,
"summary": {
"discount": 10,
"tax": 0,
"total": 60,
"subtotal": 60
},
"items": [
{
"id": "4ElJ4FEsG4PHAVNPR5qoo9",
"qty": 1,
"name": "Toy Panda",
"cost": "25",
"price": "53",
"description": "Buy a Panda",
"custom_fields": {
"sampleField": "Sample Field"
},
"custom_columns": {
"sampleColumn": "Sample Column"
},
"discount": 10,
"subtotal": 60
}
],
"total": 60
}
]
},
"tags": [
"test tag",
"sales",
"support"
]
}
}
]
I would really appreciate a tip. Thank you
If you store your JSON object into variable called obj you can access that value ("Toy Panda") with:
obj.data.pricing.tables[0].items[0].name
because tables and items are arrays.
Here is a sample example :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
</script>
Refer this link :[https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/][1]
In your case it should be something like :
var data = // your json;
var json = JSON.parse(data);
console.log(json.pricing.tables.items[0].name;

Categories

Resources