This is object data that I have stored in my this.state.profile from an API request.
What I need to do know is render the values from the keys to the web broswer. I am trying with the code below which does not work. Also how do I render the objects within side this object? This is all so confusing :(
{
"localizedLastName": "King",
"lastName": {
"localized": {
"en_US": "King"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"firstName": {
"localized": {
"en_US": "Benn"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"profilePicture": {
"displayImage": "urn:li:digitalmediaAsset:C5603AQGjLGZPOyRBBA"
},
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
How I am trying to render it:
const { profile } = this.state;
const profileList = Object.keys(profile).map((key,value)=>{
return (
<div>{key}{value.toString()}</div>
);
})
{ profileList }
try:
return (
{Object.entries(profile).map(([key,value]) => {
<div>{key} : {value.toString()}</div>
})}
)
the iteration needs to happen inside of the return.
You could build up your object outside your render call like below and just render it (elements).
var elements = [];
for (var prop in this.state.profile) {
elements.push(<div>{prop} : {this.state.profile[prop].toString()}</div>)
}
If it's not working my guess would be your state isn't initialised or your target js version doesn't support Object.entries
First of all, you need to deal with nested objects:
{
...
"firstName": {
"localized": {
"en_US": "Benn"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
}...
}
If you try to render the value on the key firstName, you will get a object as value, and React can't render objects as elements.
And if you call toString() on it, you will get [Object object] as value.
To solve this, you gonna need some recursion:
const objToString = obj => {
let result = [];
Object.keys(key => {
if(typeof obj[key] === 'object'){
let children = (<div>{key} : {objToString(obj[key])}</div>)
result.push(children)
} else
result.push(<div>{key} : {obj[key]}</div>)
})
}
...
const profileList = objToString(profile)
This should give you this something like:
...
<div>firstName:
<div>localized:
<div>en_US: Benn</div>
</div>
</div>
...
Related
The original data (old) looks like this:
Object {
"pageParams": Array [
undefined,
],
"pages": Array [
Object {
"cursor": 0,
"items": Array [
Object {
"content": "This is a users post!",
"createdAt": "2022-09-03T02:37:10.287Z",
"id": "93d13314-630e-4948-94a4-f75677afa7ba",
"likeCount": 10,
"likedByUser": false,
...
Just need to toggle likedByUser on click. passing in (id,performerId) in flatlist onclick.
Trying to map like this but I don't believe it is returning the original structure for the infinite scroll. need to return old with one changed object.
const likeHandler = (id: string, performerId: string) => {
const LikePostMutation: LikePostInput = {
id: id,
performerProfileId: performerId,
}
mutateLikes.mutateAsync(LikePostMutation).then(() => {
context.setQueryData(['fan.performer.getPostsFeed', {}], (old) => {
if (!old) return old
return old.pages.map((item: { items: any[] }) =>{
item?.items.map((item) => {
if (item?.id === id) {
let newItem = {
...item,
likedByUser: !item.likedByUser,
}
return { newItem }
}
}),
}
)
})
})
}
The error message TypeError: undefined is not an object (evaluating 'o[Symbol.iterator]') is from flatlist. I think the error message coming from view:
This is the shape of logged data after mapping incorrectly: I need it to be in the pages array and in an outer object.
}
Object {
content": "This is a users post!",
"createdAt": "2022-09-03T02:37:10.287Z",
"id": "93d13314-630e-4948-94a4-f75677afa7ba",
"likeCount": 10,
"likedByUser": true,
...
open to any suggestions on how to get better at this.
when doing immutable updates to arrays, you need to map over each item and return the same structure. infinite query structure is nested so it gets a bit boilerplat-y, but this should work:
context.setQueryData(['fan.performer.getPostsFeed', {}], (old) => {
if (!old) return old
return {
...old,
pages: old.pages.map(page) => ({
...page,
items: page.items.map((item) => {
if (item?.id === id) {
return {
...item,
likedByUser: !item.likedByUser,
}
return item
}
})
})
}
})
if you don't like the deep spreading, take a look at immer
I have a below JSON,
var original = {
"todos": [
{
"accountNo": "50190000",
"name": "Sarkar",
"vpainfo": [
{
"vpa": "log#bda",
"mccCode": "0000"
}
]
}
]
}
And am trying to add new data inside the nested array i.e., "vpainfo". I have tried using the below code and able to adding the new values inside "vpainfo".
var newdata = {"vpa":"first#bda","mccCode":"1111"};
var newObj =
Object.assign({}, original,
{
todos: original.todos.map(todoInfo=>(todoInfo.accountNo=="50190000")?[
...todoInfo.vpainfo,
newdata
]: todoInfo)
});
And the resulted object is,
{"todos":[[{"vpa":"log#bda","mccCode":"0000"},{"vpa":"first#bda","mccCode":"1111"}]]}
But few of the key and values(accountNo and name) are getting missed, how do we get the full object with the latest updated values?
You only return the array, not the actual object, hence the error.
var original = {
"todos": [
{
"accountNo": "50190000",
"name": "Sarkar",
"vpainfo": [
{
"vpa": "log#bda",
"mccCode": "0000"
}
]
}
]
}
const newdata = {"vpa":"first#bda","mccCode":"1111"};
const newObj = Object.assign({}, original,
{
todos: original.todos.map(todoInfo=>{
if(todoInfo.accountNo=="50190000"){
return {
...todoInfo,
vpainfo: [...todoInfo.vpainfo, newdata]
}
}
return todoInfo
})
});
console.log(newObj)
All those spread operators seem a little excessive...
If all you wanna do is add newdata to that existing array, then do that:
var original = {
"todos": [{
"accountNo": "50190000",
"name": "Sarkar",
"vpainfo": [{
"vpa": "log#bda",
"mccCode": "0000"
}]
}]
};
const newdata = {
"vpa": "first#bda",
"mccCode": "1111"
};
// Find the correct account.
const account = original.todos.filter(t => t.accountNo === '50190000')[0];
if (account) {
account.vpainfo.push(newdata);
}
console.log(original);
I am trying to iterate this data on vue inside the method function
{
"data": [
{
"id": 1,
"name": "Jack Daniels",
"mobile": "21223",
"start": "2021-02-25T09:16:21.000000Z",
"end": "2021-02-25T09:16:21.000000Z"
}
]
}
here is my code
async getEvents() {
try {
const response = await axios.get('/api/customers')
Object.entries(response).forEach(([key, value]) => {
console.log(`${key}:${value}`)
})
} catch (err) {
console.log(err)
}
}
and here is the output on
data:[object Object],[object Object]
any idea what went wrong and if there is better approach for iterating the data in vue.js
First of all it's not Vue question(axios/js tags).
You don't need Object.entries here (if you need to iterate data array).
Just use map for array and that's all.
const iteratedData = response.data.map((item, index) => {
console.log(`Index ${index}`);
console.log(item);
// Do what you need with data, your iteration
return item;
});
Code is fine. Here key is data and value is array of object. so to access value, here is a sample code
let response = {
"data":[{
"id":1,
"name":"Jack Daniels",
"mobile":"21223",
"start":"2021-02-25T09:16:21.000000Z",
"end":"2021-02-25T09:16:21.000000Z"
}]
};
Object.entries(response).forEach(([key,value])=>{
console.log(`${key}:${value[0].id}`)
})
Here value is an array so iterate value to get properties. It is just a sample to show logic.
I'm using a dexi.io robot to automate extraction from permit databases. The robot will accept custom javascript to parse the incoming JSON object.
This code appears to work in some cases - correctly parsing the incoming JSON - but fails in almost every circumstance. The error is cannot read property of length undefined.
Here's the test api that works: https://services.odata.org/V4/TripPinService/People
Here's the code:
var people = JSON.parse(json).value;
var arr = [];
function getCountry(member) {
try {
return member.fields.name;
} catch(err) {
return "";
}
}
for (i = 0; i < people.length; i++) {
var member = people[i];
var obj =
{
"name": member.name,
"Country": getCountry(member),
"alias": member.alias
};
arr.push(obj);
}
return arr;
Check your first line where is "json".I think you didn't defined a json file from which you are getting data.
Not sure exactly what you are doing to fetch the response, but I was able to get this working pretty easily:
fetch("https://services.odata.org/V4/TripPinService/People")
.then(response => response.json())
.then(data => {
var people = data.value;
var arr = [];
function getCountry(member) {
try {
return member.AddressInfo[0].City.CountryRegion;
} catch(err) {
return "Country Info Not Available";
}
}
for (i = 0; i < people.length; i++) {
var member = people[i];
var obj =
{
"name": member.FirstName,
"Country": getCountry(member),
"alias": member.alias
};
arr.push(obj);
}
console.log(arr);
});
Maybe this will give you some ideas.
I have checked the json from the given url. So, in your code the properties like 'member.name', 'member.alias', 'member.fields.name' doesn't exist.
Try using the exact property names from the json:
{
"#odata.context": "http://services.odata.org/V4/TripPinService/$metadata#People",
"#odata.nextLink": "https://services.odata.org/V4/TripPinService/People?%24skiptoken=8",
"value": [
{
"#odata.id": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"#odata.etag": "W/\"08D817F8EC7DAC16\"",
"#odata.editLink": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"UserName": "russellwhyte",
"FirstName": "Russell",
"LastName": "Whyte",
"Emails": [
"Russell#example.com",
"Russell#contoso.com"
],
"AddressInfo": [
{
"Address": "187 Suffolk Ln.",
"City": {
"CountryRegion": "United States",
"Name": "Boise",
"Region": "ID"
}
}
],
"Gender": "Male",
"Concurrency": 637285705159912400
}
]
}
What I am trying to say is that use the names exactly in json like 'member.UserName', 'member.AddressInfo[0].Name' etc.
I am using react-native and I am trying to pass data to child component, and after that I want to use map method for displaying user data with key value.
So i get this data after making array from object, how should i destruct it to get username etc..
PARENT COMPONENT:
render() {
let userMap = Object.entries(this.state.users).map(key => key);
return (
<ViewPager
users={userMap}
usersRetrieved={this.state.usersRetrieved}
addNewMatch={this.addNewMatch}
navigation={this.props.navigation}
/>
);
CHILD COMPONENT:
<Text>{JSON.stringify(props.users)}</Text>
How should i get username or profile_picture data?
I tried to do props.users[0].username but no luck
DATA EXAMPLE WITH 3 USERS:
{
"lwcIQTcpAae4e38hrD2K5Ar76W93": {
"email": "emilissssss#temp.lt",
"fbid": "3008*******71455",
"gender": "male",
"profile_picture": "...",
"username": "Emilis"
},
"tempuser": {
"email": "temp#temp.lt",
"fbid": 315151515,
"gender": "female",
"matches": {
"lwcIQTcpAae4e38hrD2K5Ar76W93": [Object]
},
"profile_picture": "...",
"username": "Egle"
},
"thirdUserID":{
"email": "temp#temp.lt"
"username": "thirdUserUsername"
...
}
}
Have you tried doing props.users[0][1].username instead? Since it seems to be the second value of an array inside an array
You can update userMap variable in parent component like
let userMap = Object.entries(this.state.users).map(([key, value]) => value);
This returns an array of user objects like:
[{
"email": "emilissssss#temp.lt",
"fbid": "3008*******71455",
"gender": "male",
"profile_picture": "...",
"username": "Emilis"
},
{
"email": "temp#temp.lt",
"fbid": 315151515,
"gender": "female",
"matches": {
"lwcIQTcpAae4e38hrD2K5Ar76W93": [Object]
},
"profile_picture": "...",
"username": "Egle"
},
{
"email": "temp#temp.lt"
"username": "thirdUserUsername"
...
}
]
Then in child component you can simply .map() over all users like:
{props.users.map(user => (
<Text>{user.username}</Text>
))}
Edit:
As, you need the userid also, then update userMap variable in parent component like:
let userMap = Object.entries(this.state.users);
Then in the child component, update map like:
{props.users.map(([key, user]) => (
<Text>{key}</Text>
<Text>{user.username}</Text>
))}
Or,
{props.users.map(([key, user]) => (
<Text>{key + ', ' + user.username}</Text>
))}
You can do the following thing:
{props.users.map(user => (
<Text>{user[0].username}</Text>
))}
What are you trying to do with Object.entries(this.state.users).map(key => key); ? Object.entries already returns an array so there's no need to map it afterwards like that I reckon.
Anyway, to destructure an object in js:
const obj = {
a: "value",
b: "other value",
}
const {a,b} = obj
// a "value", b "other value"
Note that the variable and the key should be named the same.
And now you have a and b as constants available in your code.
In your child component you could have smth like this:
render() {
let users = props.users
return users.map(user => {
const {username, email} = user; // destructure whatever you want
return <Text>{email} {username}</Text> // display it the wy you want
});
}
Array appears to be tied up several times.
The value you want is in the second index of the second array.
{props.users.map(user => (
<Text>{user[1].username}</Text>
))}