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;
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);
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)
My json response is
{"status": true, "data": {"basic": {"name": "haji", "dob": "2018-01-01", "gender": "male", "created_at": "2018-01-08T13:38:49.767Z", "firstname": "Ah", "lastname": "Sh", "userType": "Agent", "actor": 1, "username": "ashu", "contact": {"email": "ah#gmail.com", "phone": 863249517, "address": null}, "is_new": false, "is_email_verified": true, "is_phone_verified": true}, "wallet": {"amount": 144.0, "tds": 6.0}, "clan": null, "balance_lisitings": 48, "clan_status": false, "listings": [{"pid": 36, "name": "Labs", "website": "Labs", "category": {"name": "Education"}, "location": {"lat": 9.52766533190131, "lon":
76.8221354484558, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "ah#gmail.com", "phone": 8986234851, "address": {"country": "India", "state": "Kerala", "name": "aloh", "pincode": 686895, "streetAddress": "Kottayam\nKanjirappally", "locality": "Koovappally", "city": "Koovappally"}}, "about": " IT company."}, {"pid": 37, "name": " Louis", "website": "ouis", "category": {"name": "Education"}, "location": {"lat": 10.0273434437709, "lon": 76.5288734436035, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "soew988#gmail.com", "phone": 989756240, "address": {"country": "India", "state": "Kerala", "name": "allen45", "pincode": 686518, "streetAddress": "Sppally", "locality": "Koovappally", "city": "Koovappally"}}, "about": "fsdbgfnvb cvc"}], "total_listings": 2}}
========================================================================
My vue js script is
<script>
new Vue({
el: '#listings' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
$.ajax({
url: "https://",
method: "GET",
dataType: "JSON",
success: function (e) {
self.data = e.data;
},
});
})
},
})
</script>
My html code is
<div id="listings">
<h1>{{basic.name}}</h1>
<h2>{{basic.dob}}</h2>
like wise all data
</div>
Can anybody please help me to display the same. I am weak in js. This is the data I am getting I need to display the above data in vue js. I store all the data to a variable data[]. From it, how can I able to display the same?
One thing you'll need is a v-if to keep things from rendering when there's no data.
You have a data variable and basic is inside it. As you have it, all the things you want to include are inside it, so you will have a lot of things like data.basic.name.
const e = {
"status": true,
"data": {
"basic": {
"name": "haji",
"dob": "2018-01-01",
"gender": "male",
"created_at": "2018-01-08T13:38:49.767Z",
"firstname": "Ah",
"lastname": "Sh",
"userType": "Agent",
"actor": 1,
"username": "ashu",
"contact": {
"email": "ah#gmail.com",
"phone": 863249517,
"address": null
},
"is_new": false,
"is_email_verified": true,
"is_phone_verified": true
},
"wallet": {
"amount": 144.0,
"tds": 6.0
},
"clan": null,
"balance_lisitings": 48,
"clan_status": false,
"listings": [{
"pid": 36,
"name": "Labs",
"website": "Labs",
"category": {
"name": "Education"
},
"location": {
"lat": 9.52766533190131,
"lon": 76.8221354484558,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "ah#gmail.com",
"phone": 8986234851,
"address": {
"country": "India",
"state": "Kerala",
"name": "aloh",
"pincode": 686895,
"streetAddress": "Kottayam\nKanjirappally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": " IT company."
}, {
"pid": 37,
"name": " Louis",
"website": "ouis",
"category": {
"name": "Education"
},
"location": {
"lat": 10.0273434437709,
"lon": 76.5288734436035,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "soew988#gmail.com",
"phone": 989756240,
"address": {
"country": "India",
"state": "Kerala",
"name": "allen45",
"pincode": 686518,
"streetAddress": "Sppally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": "fsdbgfnvb cvc"
}],
"total_listings": 2
}
};
new Vue({
el: '#listings',
data: {
data: [],
},
mounted() {
const self = this;
self.data = e.data;
},
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="listings" v-if="data.basic">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>
Any data nested inside the data (and computed) property is available in the template between the {{ and }} tags.
For example:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ msg }}</h2>'
data: function () {
return {
msg: 'default message'
}
},
So in your case, with nested properties it is exactly the same as you would access them in javascript:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ data.wallet.amount }}</h2>'
'<h2 v-for="listing in listings" :key="listing.pid">{{ listing.name }}</h2>'
}
data: function () {
return {
data: []
}
},
Note
The data object should be returned from a function, from the original docs:
When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data. (https://v2.vuejs.org/v2/api/#data)
Further reading
I would advise you to read the Vue guide, especially the sections about
Declarative Rendering, Conditionals and Loops and Template Syntax
EDIT
While I was writing my answer, I see you edited your question.
Change your html to this:
<div id="listings">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>
this is my controller in angularjs
(function(){
"use strict";
angular
.module("testApp")
.controller("testAppCtrl", function($scope , $http){
$http.get('/data/testapp.json').then(function(data){
//$scope.testapps = testapp.data;
console.log(data);
});
});
})();
and i face this error
angular.js:13708 SyntaxError: Unexpected token p in JSON at position 130
how can i fix it?
Your json file has invalid code.You are missing quots around posted and contact also in the and extra , is inserted this should be like
[{
"id": "1",
"title": "test1",
"description": "test 1 test 1 test 1 test 1 test 1 ",
"price": "2000",
"posted": "2015-10-24",
"contact": {
"name": "test1 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "200"
}, {
"id": "2",
"title": "test2",
"description": "test 2 test 2 test 2 test 2 test 2 ",
"price": "2000",
"posted": "2015-10-24",
"contact": {
"name": "test2 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "200"
}, {
"id": "3",
"title": "test3",
"description": "test 3 test 3 test 3 test 3 test 3 ",
"price": "3000",
"posted": "2015-10-24",
"contact": {
"name": "test3 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "100"
}, {
"id": "4",
"title": "test4",
"description": "test 4 test 4 test 4 test 4 test 4 ",
"price": "4000",
"posted": "2015-10-24",
"contact": {
"name": "test4 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "40"
}, {
"id": "5",
"title": "test5",
"description": "test 5 test 5 test 5 test 5 test 5 ",
"price": "5000",
"posted": "2015-10-24",
"contact": {
"name": "test5 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "290"
}, {
"id": "6",
"title": "test6",
"description": "test 6 test 6 test 6 test 6 test 6 ",
"price": "6000",
"posted": "2015-10-24",
"contact": {
"name": "test6 mona",
"phone": "98765678",
"email": "test#gmail.com"
},
"categories": [
"vehicle",
"test"
],
"image": "1.jpg",
"views": "10"
}]
I have a HTML code like below which I use AngularJS framework within it:
<select name="choose-staff" ng-model="admin_times[0].user" ng-change="update(reserve.staff)" id="choose-staff">
<option ng-repeat="value in staff | unique:'employee.user.username'" value="{[{ value.employee.user.username }]}">{[{ value.employee.user.first_name }]} {[{ value.employee.user.last_name }]}</option>
</select>
And I get an error like this:
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: value in staff | unique:'employee.user.username', Duplicate key: string:ب, Duplicate value: ب
And if I use track by $index it destroys my desired structure and when I click one of options, the rest of them get vanished.
[
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Haircut",
"fa_title": "کوتاهی مو"
},
"allocated_time": 60,
"booked_no": "XG4OCX81"
},
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 25,
"booked_no": "1AY3F24G"
},
{
"employee": {
"user": {
"id": 2,
"first_name": "رضا",
"last_name": "ولیمرادی",
"user_profile": {
"id": "9d9be03a-f840-46ea-a21e-76cd5775a886",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:10.312340Z",
"location": "36.03133177633187,51.328125"
},
"username": "reza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": false
},
"service": {
"en_title": "Yellow",
"fa_title": "زرد"
},
"allocated_time": 15,
"booked_no": "H989M93X"
},
{
"employee": {
"user": {
"id": 1,
"first_name": "علیرضا",
"last_name": "غفاری",
"user_profile": {
"id": "884b36e3-7bad-466f-afee-25801572b834",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:39.522362Z",
"location": "32.24997445586331,53.26171875"
},
"username": "alireza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 20,
"booked_no": "O5KLFPZB"
}
]
I don't like the redundancy of employee.user.username
Looks to me like the unique value in each object is the booked_no.
In which case you should use track by value.booked_no