How do you access all values in JSON array? - arrays

The only data I can access right now is the beginning part of the array:
[
{
/*start*/
"username" : "Bob",
"password":"123456",
"bio":"Hi",
/*End*/
"data":
[
{
"pet" : "dog",
"age" : "20",
"city" : "5"
},
{
"pet" : "cat",
"age" : "18",
"city" : "7"
}
]
}
]
I can also access part of the data array, but I am trying to access all of it. For example: {item.data[1].pet}. I tried using a for loop but was unsuccessful with that. I am also using react-native flat list and doing dataSource: responseJSON.data didn't work for me either. I'm sure there has to be a way to access all of the values of petinstead of just one each time, I just don't know how to.
Also since I am a beginner any tips will be gladly appreciated.
EDIT: Attempts at trying to loop from outside the JSX:
var itemList = [];
for (var i = 0; i < responseJSON[0].data.length; i++) { itemList.push(<Text> {responseJson[0].data[i].pet}</Text>); }
I put that out of the render() Then I take itemList and stick it here:
<FlatList
data={ this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <View>
{itemList}
</View>
}
keyExtractor={(item, index) => index}
/>
Now it's not understanding that itemList is a variable. I'm getting a syntax error.
EDIT 2: Thanks to everyone the only thing I need help with is putting a variable inside of componentDidMountin React Native.

I have no experience with React but from what I've found it seems it should be done this way:
const responseJson = [
{
/*start*/
"username" : "Bob",
"password":"123456",
"bio":"Hi",
/*End*/
"data":
[
{
"pet" : "dog",
"age" : "20",
"city" : "5"
},
{
"pet" : "cat",
"age" : "18",
"city" : "7"
}
]
}
];
const listItems = responseJson[0].data.map((details) =>
<li>{details.pet}</li>
);
ReactDOM.render(
<ul>{listItems}</ul>,
document.getElementById('root')
);
The output I get is:
dog
cat

You can do it like this in javascript:
var json = {"data":[{"pet":"dog","age":"20","city":"5"},{"pet":"cat","age":"18","city":"7"}]};
for (var i = 0; i < json.data.length; i++) {
var object = json.data[i];
console.log(object);
console.log(object.pet, object.age, object.city);
}

Try this loop :
for (var i = 0; i < responseJSON[0].data.length; i++) {
alert(responseJSON[0].data[i].pet);
}
Working example here :
https://plnkr.co/edit/c1sZYKrBWHFJOKwHEMbU?p=preview

Why don't you convert all the data in the responseJson to objects using Lodash Library and then take the data object from it and assign it to a variable and then convert it back to an array. And after that you change the data source to that array you get
See the Documentation of Lodash here

Related

How to create the sectiondata in the react native sectionlist

I want show the data from my API use Sectionlist in the react native
but I have no idea how to generate the sectionData.
I think my data is too complex to understand and let me confuse.
The struct like below
"Info": [
{
"Name": "test1",
"Data": [
{
"sss": "1215",
"aaa": "1010133000001",
},
{
"sss": "1215",
"aaa": "1010133000001",
}
]
},
{
"Name": "test2",
"Data": [
{
"sss": "1215",
"aaa": "1010133000001",
},
{
"sss": "1215",
"aaa": "1010133000001",
}
]
}
]
}
I want show the SectionHeader use Nameand show the Contents use Data.
Now I can get data use potion of code like below. How can I go on? Thank you!
for (let idx in jsonData) {
let Item = jsonData[idx];
console.log(Item.Name)
for (let index in Item.Data) {
Item2 = Item.Data[index];
console.log(Item2.sss)
}
}
First, you have to update your data array,
let newArray = []
for (let item in jsonData) {
let dict = {
title: item.Name,
data: item.Data
}
newArray.push(dict)
}
After the above code, you will get the array for section list.
Then use this like the following,
...
<SectionList
renderItem={({item, index, section}) => <Text key={index}>{item.sss}</Text>}
renderSectionHeader={({section: {title}}) => (
<Text style={{fontWeight: 'bold'}}>{title}</Text>
)}
sections={this.state.data}
keyExtractor={(item, index) => item + index}
/>
...
The 'this.state.data' is your new array.
And renderItem is used for rendering section data
And renderSectionHeader is used for rendering section header.
provide an array of items, this will spit out the section data
// maps it's an array of objects
// groupBy to extract section headers
let dataSource = _.groupBy(maps, o => o.name);
// reduce to generate new array
dataSource = _.reduce(dataSource, (acc, next, index) => {
acc.push({
key: index,
data: next
});
return acc;
}, []);
return dataSource;

es6 Loop through object array and aggregate unique values from key pair (cleanest way)

What's the cleanest and es6 native (if possible) way to loop through a object array to grab each unique value. Example would like this :
[{
"name" : "joe",
},
,{
"name" : "jean",
},
{
"name" : "joe",
},
{
"name" : "joe",
},
{
"name" : "mike",
}]
and in my results I want to see only : joe, jean, mike (only unique values, no dupes)
Since you mentioned ES6, it seems like a Set object would be what you want since it will do the uniqueness part for you and should do so fairly efficiently:
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
let uniqueNames = Array.from(new Set(objs.map(item => item.name)));
console.log(uniqueNames);
Run this snippet to see the results.
a = [{name:"joe"},{name:"jean"},{name:"joe"},{name:"joe"},{name:"mike"}]
console.log(_.uniq(_.map(a, 'name'))) // Lodash 0.1.0
console.log([...new Set(a.map(o => o.name))]) // ES6
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.4/lodash.min.js"></script>
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
var uniqueNames = objs.map( obj => obj.name )
.filter( (name, idx, arr) => { return arr.indexOf(name) === idx; } );
The .map extracts an array of the name values, and the .filter returns only the unique elements (first instances only).

Cannot get data from a js array with Node js

I have a js object array like this.
[
{
name:"Japanilainen ravintola Koto",
rating:3.9,
photo:[
{
height:2160,
html_attributions:[
"Hannes Junnila"
],
photo_reference:"CoQBdwAAAMDlivT0nOnYg8jC1txZ3RbfBR59XvKN0WphDbRVUXaUTQclzzaIaXJ8-p7s3x_aG67AUsM_HLNML6pzGl3v_wV2D-eudH_3wy2cB1ROrRgGcGyf4lRuNpE3WwXYbYZu6EK8oEPiJ5B17Lybj-eVbYM2EgVVBgOrUJhsblY1mfxWEhAZ4oHCFakH-hgkbksfGa2uGhQe4aUeOrS2isAir01KUwQ7N3Ce2Q",
width:2269
}
]
},
{
name:"Kin Sushi Helsinki",
rating:4.2,
photo:[
{
height:2988,
html_attributions:[
"Stephan Winter"
],
photo_reference:"CoQBdwAAAN4iMumSbQjtRnJIH1AKRdbSfnI02WGh11r1xaVnZl1ohebKp6zpAS4mmJFqTagrIqUJ39kzulVI0sz2UzzfaVdsAFc5f80PnOCzSLqL5gnpsqv90dVJIqUWD3Bcc9TgYPPs3oGwyekkOsmjQ59o9yqdoF5GzrpaKkojhMNLxpfzEhBKpRkA2CzINpUzAAe3e90TGhQ_KbYCmtJYLfVGIu1kZkzQIAwE4A",
width:5312
}
]
}
]
I get this array above by doing this for each.
response.results.forEach((entry)=>{
var restaurantName = {
"name" : entry.name,
"rating" : entry.rating,
"photo_reference" : entry.photos
}
arr.push(restaurantName);
});
res.send(arr);
And I send the array to my browser so I can see it.
What I am trying to do is to get photo_reference from the entry.photos
I tried entry.photos[0].photo_reference and many more ways and in all of them I am getting a cannot read properly, and now I am not sure how to get that information out.
I edited some of the variable names to make it easier to simulate here, but just map the objects in the photo arrays to their references, and you'll get an array of photo references.
const data = [
{
name:"Japanilainen ravintola Koto",
rating:3.9,
photo:[
{
height:2160,
html_attributions:[
'Hannes Junnila'
],
photo_reference:"CoQBdwAAAMDlivT0nOnYg8jC1txZ3RbfBR59XvKN0WphDbRVUXaUTQclzzaIaXJ8-p7s3x_aG67AUsM_HLNML6pzGl3v_wV2D-eudH_3wy2cB1ROrRgGcGyf4lRuNpE3WwXYbYZu6EK8oEPiJ5B17Lybj-eVbYM2EgVVBgOrUJhsblY1mfxWEhAZ4oHCFakH-hgkbksfGa2uGhQe4aUeOrS2isAir01KUwQ7N3Ce2Q",
width:2269
}
]
},
{
name:"Kin Sushi Helsinki",
rating:4.2,
photo:[
{
height:2988,
html_attributions:[
'Stephan Winter'
],
photo_reference:"CoQBdwAAAN4iMumSbQjtRnJIH1AKRdbSfnI02WGh11r1xaVnZl1ohebKp6zpAS4mmJFqTagrIqUJ39kzulVI0sz2UzzfaVdsAFc5f80PnOCzSLqL5gnpsqv90dVJIqUWD3Bcc9TgYPPs3oGwyekkOsmjQ59o9yqdoF5GzrpaKkojhMNLxpfzEhBKpRkA2CzINpUzAAe3e90TGhQ_KbYCmtJYLfVGIu1kZkzQIAwE4A",
width:5312
}
]
}
]
const arr = []
data.forEach((entry)=>{
var restaurantName = {
"name" : entry.name,
"rating" : entry.rating,
"photo_reference" : entry.photo.map(x => x.photo_reference)
}
arr.push(restaurantName);
});
console.log(arr);
entry.photoes is not defined in your response.results object array.. did you mean to access it as entry.photo (inside your foreach function) ?

Find Firebase Child from Array Values - xcode 8 / swift 3

Id like to get a snapshot with snapshot.key as the UID if the snapshot.value is "pending". Store that into an array. Then i'd like to loop through the array of UID and pull of all the details from .child("users") i.e. "email", "name" & "profileURL". Not sure what the best route is here. Do I store the snapshot into a dictionary then filter dictionary to "pending" or do this within the snapshot call itself?
friends & users JSON structure in my Firebase Database (as below;)
{
"friends" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
},
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : "pending",
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : "pending",
"lNI9FxCErqMUNiW43yiDpkNoljg1" : "pending"
},
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
},
"lNI9FxCErqMUNiW43yiDpkNoljg1" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
}
},
"users" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : {
"email" : "orsrzlqwmt_1488724206#tfbnw.net",
"name" : "Karen Alaedidibgghi Liangescu",
"profileURL" : "someURL"
},
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : {
"email" : "rbwimniovp_1488724216#tfbnw.net",
"name" : "Patricia Alaefhcbebjid Warmansen",
"profileURL" : “someURL”
},
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : {
"email" : "bhulxppahm_1488724211#tfbnw.net",
"name" : "Harry Alaeejdjagjga Greenestein",
"profileURL" : "someURL"
},
"lNI9FxCErqMUNiW43yiDpkNoljg1" : {
"email" : "axtinlmwes_1488724221#tfbnw.net",
"name" : "Maria Alaefehgadbdg Valtchanovsky",
"profileURL" : "someURL"
}
}
}
Any help greatly appreciated. Cheers!
Here's how you'd get started, once you have your parsed data you can use different methods to filter it which you can look up through different stackoverflow questions answered in the past.
let dbRef = FIRDatabase.database().reference.child("friends")
dbRef.observeSingleEvent(of: .value, with: { snapshot in
if let data = snapshot.value as? [String: [String: String]] {
for user in data {
// You'll now have a dictionary with neatly formatted values you can filter
}
}
})

Conditional selecting from a JSON array

I'm trying to select and display specific JSON data within an array. The data looks like this:
{ "thingys" : [
{
"type" : "thingy1",
"text" : "this is thingy1"
},
{
"type" : "thingy2",
"text" : "this is thingy2"
},
{
"type" : "thingy3",
"text" : "this is thingy3"
}
]}
I'm using json2html, and I would normally use something like
{"tag":"div","html":"${thingys.text}"}
This would be fine, but I want to be able to specify that I want ${thingys.text} where ${thingys.type} == "thingy3". How would I go about doing this?
best way to achieve something like this would be to include an inline function to process the the "thingys" Something like this
var transforms = {
'main': {"tag":"div","children":function() {
var out = [];
for(var i=0; i < this.thingys.length; i++)
if(this.thingys[i].test == "thingy3") out.push(this.things[i]);
return( json2html.transform(out,transforms.thing) );
}},
'thing':{"tag":"div","html":"${text}"}
};

Resources