Related
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);
I am getting below response on hitting DoctorData.api and want to sort them all with their 'ID'. Can someone show me how to sort the Output JSON data and display it same format.
Kindly Excuse my coding skills, this is my second test case. I am new to JS.
var doctorIDgeturl = geturl.geturls.getapiUrl; //'getapiUrl' is Doctor Get API
var res = await api.getRequest(doctorIDgeturl);
logger.logger().info('GET_data = ', JSON.stringify(res.data, null, 2));
var rescount = Object.keys(res.data.data.doctorList); //doctorList is the API response object for above GET API
console.log("This is Sorted Id: ");
const sortedResponse = sort(res.data, r => r.doctorListModels.associateId, ['asc']) //using ascending order to sort
console.log(sortedResponse);
Current output:
{
"message": "Record Found",
"data": {
"DoctorsList": [
{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}
Expected output after sorting:
{
"message": "Record Found",
"data": {
"DoctorsList": [
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
},
{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
}
parseInt(r.doctorListModels.associateId) or +r.doctorListModels.associateId
it seems like it sorts the id as string not number
Sorry I can't comment because of low reputation, but here is solution.
const obj = {
"message": "Record Found",
"data": {
"DoctorsList": [{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}]
}
}
const sortedResponse = obj.data.DoctorsList.sort(function(a, b) { return parseInt(a.id) - parseInt(b.id) });
console.log(sortedResponse)
const obj = {
"message": "Record Found",
"data": {
"DoctorsList": [{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}
]
}}
obj.data.DoctorsList = obj.data.DoctorsList.sort((a, b) => parseInt(a.id) > parseInt(b.id));
console.log(obj)
I have a REST API from which i am fetching the json data and storing them in array. The API looks like below:
[
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
]
Some of the data have "parent" field.The value in the "parent" field is the "id" of the other data. Now i want to store these data which have reference in the "parent" field of other data in a separate array. For example:
The data with id=101 has "parent" key with value 105 which in turn is the id of the 3rd data.So the data with id=105 should be stored in separate array.
How can i do in a simple and scalable way?
Try
let parents = data.filter(d=> data.some(c=> c.parent==d.id));
let data = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let parents = data.filter(d=> data.some(c=> c.parent==d.id));
console.log(parents);
To have O(2n) complexity first put parents id to some hash table and then filter
let data = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let hash = {};
data.forEach(d=> hash[d.parent]=d);
let parents = data.filter(d=> d.id in hash);
console.log(parents);
You can use map method and store elements into Map collection to have O(1) when you map items:
const maps = new Map(fooArray.map(o=> [o.id, o]))
const result = fooArray.map(({parent, ...rest}) => {
let obj = {...rest};
parent ? (obj.parent = [maps.get(parent)]) : null;
return obj;
})
console.log(result);
An example:
const fooArray = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
]
const maps = new Map(fooArray.map(o=> [o.id, o]))
const result = fooArray.map(({parent, ...rest}) => {
let obj = {...rest};
parent ? (obj.parent = [maps.get(parent)]) : null;
return obj;
})
console.log(result);
You can also collect all parent ids and then find records which has the same id as some parent:
let par_ids = [];
records.forEach(pid =>{
for (let [key, value] of Object.entries(pid)) {
key == 'parent' ? par_ids.push(value) : null;
}
})
let res = records.filter(ob => par_ids.includes(ob.id))
let records = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let par_ids = [];
records.forEach(pid =>{
for (let [key, value] of Object.entries(pid)) {
key == 'parent' ? par_ids.push(value) : null;
}
})
let res = records.filter(ob => par_ids.includes(ob.id))
console.log(res)
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;
I have a set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below.
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }]
var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" }],
"5": [{ "Id": "5", "name": "zzz", "age": "59" }]}]
You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need
var data= [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }];
console.log(data.reduce(function(result, current) {
result[current.Id] = result[current.Id] || [];
result[current.Id].push(current);
return result;
}, {}));
Try
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }], output;
output = [origObj.reduce((a,c) => (a[c.Id]=(a[c.Id]||[]).concat(c),a) ,{})];
console.log(output);