I have one json file which contains multiple objects inside another object,I want to iterate there key and values in my HTML Page:
Exemple :
{
"firstName": "Ayoub",
"lastName": "Gammar",
"mntDc": 502.0,
"childs": [
{
"firstName": "Rafik",
"lastName": "Mansour",
"mntDc": 500.0,
"username": "user3"
},
{
"firstName": "Ahmed",
"lastName": "Makni",
"mntDc": 1.0,
"childs": [
{
"firstName": "ALi",
"lastName": "hama",
"mntDc": 500.0,
"username": "admin"
}
],
"username": "user2"
}
],
"username": "user1"
}
Angular Methode :
this.usrerArbre.getArbre().subscribe(data=>{
console.log('data'+data);
this.arbreUSer=data;;
},error1 => {
console.log(error1)
})
}```
I don't understand which key you want to iterate. If you want to iterate the childs key then you can iterate it like this:
(data.childs||[]).forEach((item, index) {
console.log(item, index);
});
But if you want to iterate the whole object then you can get its keys from:
let keys = Object.keys(data);
(keys||[]).forEach(function(item, index) {
console.log(data[item], index); // You will get the each object key value here
});
Try this,
this.usrerArbre.getArbre().subscribe(data=>{
console.log('data'+data);
this.arbreUSer=data.childs;
},error1 => {
console.log(error1)
})
}
.html
<div *ngFor="let data of arbreUSer">
<p>{{data.firstName}}</p>
<p>{{data.lastName}}</p>
<p>{{data.mntDc}}</p>
<p>{{data.userName}}</p>
</div>
Here is a short solution:
var result = Object.entries(data).map(([key, value]) => ({key,value}));
//console.log(result);
Related
I implemented i18n with useTranslation and tried to make it easier for json path to be written.
JSON
{
"userInfo":{
"name": "Name",
"lastname": "Last Name"
},
"sideMenu:{
"home":"Home"
}
}
So now when I try to access translated text I go
t("userInfo.name", "Name")
I tried to make a function that will recursively call it self and create the object like this
object = {
userInfo: {
name: {
key:"userInfo.name",
value:"Name"
},
lastname: {
key:"userInfo.lastname",
value:"Last name"
},
},
sideMenu: {
home: {
key:"sideMenu.home",
value:"Home"
}
}
}
so now I could access like this
t(object.userInfo.name.key, object.userInfo.name.value)
I tried using entries and fromEntries function but I simply cant get hold of the logic behind it.
I made it work with a recursive function so now, no matter the number of nested objects function will return a new object with key and value items.
You can see working snippet with json file i used for the project.
let en = {
"userInfo":{
"name": "Name",
"lastname": "Last Name",
"gender": "Gender",
"age": "Age",
"location": "Location",
"address": "Address",
"city": "City",
"login": "Login",
"about": "About"
},
"comboBox": {
"loading": "Loading...",
"loadmore": "Load More"
},
"error": {
"errormsg": "Ooops, it seems you are not authenticated to see this...",
"errormsgsub": "Get back and try again",
"errorbtn": "Back to Safety",
"alertmsg": "You should login first!"
},
"sideMenu": {
"home": "Home",
"logout": "Logout",
"croatian": "Croatian",
"english": "English",
"hello": "Hello"
},
"loadingPage": {
"load": "Loading...",
"loadsub": "Please wait"
}
}
function languageRecursion(data, key){
if (typeof data === 'object') {
return Object.fromEntries(
Object.entries(data).map(([ikey, value]) => {
return [ikey, languageRecursion(value, key ? `${key}.${ikey}` : ikey)];
})
);
}
return { key: key, value: data };
}
let locale = languageRecursion(en)
console.log("path",locale.userInfo.about.key)
console.log("value", locale.userInfo.about.value)
With this working now you can call languages with i18next useTranslation hook faster and easier.
t(locale.userInfo.name.key)
For example this is the json which I am receiving,
{
"events": [...
],
"total": 12341,
"students": [
{
"id": 1,
"first_name": "John",
"last_name": "Apple"
},
{
"id": 2,
"first_name": "Bob",
"last_name": "Banana"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Carrot"
}
]
}
And I want to transform the data to the following form, and return it as an observable
[
{
"first_name": "John",
"last_name": "Apple"
},
{
"first_name": "Bob",
"last_name": "Banana"
},
{
"first_name": "Charles",
"last_name": "Carrot"
}
]
I have tried the following, but it returns undefined.
getStudentsName(): Observable<any> {
const requestUrl = this.rootURL + `students/`;
let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
return studentsInfo.pipe(map(students => {students.first_name, students.last_name}));
}
returns undefined when subscribing to observable
this.getStudentsInfoService.getStudentsName()
.subscribe((result) => console.log('here', result));
It looks like it can't find students. Try this :
return studentsInfo.pipe(map(s => { return {
first_name: s.first_name,
last_name: s.last_name,
}}));
Your problem is, that students is an array, but you handle it as an object. You need to add a nested map: 1 for rxjs, 1 for the array
return studentsInfo.pipe(
map(studentsArray => studentsArray.map(student => ({
first_name: student.first_name,
last_name: student.last_name
}))),
);
PS.: Using types instead of any would have shown you that. Neither you nor the other responders saw this issue due to missing typing.
Here is a short code snippet.
const object = {
"total": 12341,
"students": [
{
"id": 1,
"first_name": "John",
"last_name": "Apple"
},
{
"id": 2,
"first_name": "Bob",
"last_name": "Banana"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Carrot"
}
]
}
let arr: any = [];
object.students.forEach(person => arr.push(
{
"first_name": person.first_name,
"last_name": person.last_name
}))
console.log(arr)
[LOG]: [{ "first_name": "John", "last_name": "Apple" },
{ "first_name": "Bob", "last_name": "Banana" }, { "first_name": "Charles", "last_name": "Carrot" }]
You can iterate over students with a foreach loop and then create a new json which you then push in your new array
this.http.get<any>(requestUrl).pipe(map(o => o.students.foreach(person => arr.push({
...}));
The Problem
The Problem is with your how you return your observable
Lets break the code down
let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
In the above studentsInfo will be of type Observable<any>
Next line is as per below
return studentsInfo.pipe(
map(students => {
students.first_name, students.last_name
}
));
Lets have a look at the below section
{
students.first_name, students.last_name
}
This part of the section actually has no return statement hence by default javascript returns undefined!
Solution
To use arrow function without a return statement, you will need to wrap {} inside a () like below
students => ({ })
Below will work
getStudentsName(): Observable<any> {
return this.http.get<any[]>(`${this.routeURL}/students`).pipe(
map(o => o.students));
}
I want to display nested JSON data in a react-table.
I tried it like this:
render() {
const columns = [{
//Not Displaying
Header: 'Owner ID',
id: 'ownerid',
accessor: '_links.customer.href.ownerid', // <- i think this is wrong
Cell: this.renderEditable
},
{
//Displaying
Header: 'Price',
accessor: 'price',
Cell: this.renderEditable
}, {
The data i am getting back and have bound to the table is structured as follows:
[
{
"id": 1,
"date": "20.07.2019",
"price": 3.2,
"customer": {
"ownerid": 1,
"firstname": "John",
"lastname": "Johnson"
}
}
]
Here i am using the columns array:
import ReactTable from "react-table";
<ReactTable data={this.state.offers} columns={columns}
filterable={true} pageSize={10}/>
Binding the data:
fetchOffers = () => {
const token = sessionStorage.getItem("jwt");
fetch(SERVER_URL + 'api/offers',
{
headers : {'Authorization':token}
})
.then((response) => response.json())
.then((responsteData) => {
this.setState({
offers: responsteData._embedded.offers,
});
console.log(this.state);
})
.catch(err=> console.error(err));
}
The data i am using after binding:
Check the Accessors documentation. It has several examples for complex data structure.
I don't see _links or href in your sample data. So I think that you need just:
accessor: 'customer.ownerid'
The data structure from the console screenshot doesn't match your sample data. And it doesn't seem to contain ownerid. Try accessor: '_links.customer.href' to check whether it outputs anything to the table.
I figured it out.
I called the endpoint "localhost:8080/api/offers" and saved the following response:
"offers": [
{
"date": "20.07.2019",
"price": 3.2,
"_links": {
"self": {
"href": "http://localhost:8080/api/offers/1"
},
"offer": {
"href": "http://localhost:8080/api/offers/1"
},
"customer": {
"href": "http://localhost:8080/api/offers/1/customer"
}
}
}
]
there is no customer object
But when i call "localhost:8080/offers" i get:
[
{
"id": 1,
"date": "20.07.2019",
"price": 3.2,
"customer": {
"ownerid": 1,
"firstname": "John",
"lastname": "Johnson"
}
}
]
i changed the URI in my project and now the number is displaying.
I still don't know why i get data from "../api/offers" but i will research.
I had to access a nested object and display it with some styling, and this ended up working for me:
(Note: I was using typescript, so some of the typing might not be necessary)
{
Header: 'Thing To Display',
accessor: 'nested.thing.to.display',
Cell: ({ row }: { row: Row }) => (
<p>{row.values['nested.thing.to.display']}</p>
),
}
I want to transform my data from one json structure to another. What is the best way to do it?
Here is my original resource (customer) structure is:
{
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
I want to change it to:
{
"id": "123",
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.
If customer object is array of object then below will help you to get desire format result
var result = customerObj.map(x => {
return {
id: x.id,
name: x.data.name,
status: x.data.status,
contacts: x.data.contacts
};
});
here I have used Object.assign() it will be helpful to you
var arr={
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);
You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.
Example code
function formatter(oldFormat) {
Object.assign(oldFormat, oldFormat.data);
delete oldFormat.data;
}
let parsedData = JSON.parse(Oldjson);
//Take care for array of results or single result
if (parsedData instanceof Array) {
parsedData.map(customer => formtter(customer));
} else {
formatter(parsedData);
}
let newJson = JSON.stringify(parsedData);
console.log(newJson);
Edit
I made the formatter function cleaner by using Kalaiselvan A code
when I did
loadPeople(){
this.myService.load().then(data => {
this.people = data;
alert(this.people);
});
}
it alerts json as :
{
"status": "true",
"statusCode": 200,
"response": [{
"user_id": "92",
"firstname": "joy",
"lastname": "Panchal",
"email": "joy#gmail.com",
"password": "7Y7+K0vZIVWPDUQH++Iu+/+tMZ",
"user_type_id": "1"
}, {
"user_id": "89",
"firstname": "mark",
"lastname": "haris",
"email": "mark#gmail.com",
"password": "4JICqnTkR8ysTI+nQQ+rpfAf7e",
"user_type_id": "1"
}]
}
now i am trying to access "response" by
loadPeople(){
this.myService.load().then(data => {
this.people = data.response;
alert(this.people);
});
}
but it alerts as "undefined" .
can anyone tell where i am missing ??
you can access like this. please try.
`loadPeople(){
this.myService.load().then(data => {
this.people = JSON.parse(data.response);
alert(this.people);
});
}`
you need parse JSON first:
this.myService.load().then(data => {
let res = JSON.parse(data);
this.people = res.response;
alert(this.people);
});
}