I have an object of object array in json format.I want to remove one object form this object array using vuejs.
vuejs
export default {
components: { leftmenu, countDown, timer, Header },
data() {
return {
this.orders = {"data":{"175":{"details":[{"order_id":175,"item_id":1,"item_name":"pizza"},{"order_id":175,"item_id":2,"item_name":"burger"}]},"173":{"details":[{"order_id":175,"item_id":1,"item_name":"pizza"}]}}}
};
},
}
I have tried to remove object which have key 175 using below code.But did not work.
const filtersList = Object.keys(this.orders.data).filter(
(element) => element !== index
);
this.orders = filerslist
You can use the delete keyword (documentation here) to remove keys from objects
const orders = {
"data": {
"175": {
"details": [{
"order_id": 175,
"item_id": 1,
"item_name": "pizza"
}, {
"order_id": 175,
"item_id": 2,
"item_name": "burger"
}]
},
"173": {
"details": [{
"order_id": 175,
"item_id": 1,
"item_name": "pizza"
}]
}
}
}
delete orders.data["175"]
console.log(orders)
Related
i am getting array of objects from api.
The data looks like this.
Array [
Object {
"code": 230,
"name": "טרגט",
"themeColor": "#009fe8",
},
Object {
"code": 270,
"name": "קוסל",
"themeColor": "#9c3ab4",
},
Object {
"code": 465,
"name": "מעיין",
"themeColor": "#0bb694",
},
Object {
"code": 485,
"name": "מעיין תיכונים",
"themeColor": "#009fe8",
},
Object {
"code": 700,
"name": "משרד החינוך",
"themeColor": "#9c3ab4",
},
Object {
"code": 701,
"name": "מ.החינוך אולפני",
"themeColor": "#0bb694",
},
Object {
"code": 702,
"name": "חינוך התישבותי",
"themeColor": "#009fe8",
},
Object {
"code": 984,
"name": "לא לגעת -חברת הדגמה ",
"themeColor": "#9c3ab4",
},
]
i want to add a dropdown which contain items as array of objects "name" value from
api.
i am using RNPickerSelect from "react-native-picker-select";
const [selectedComp, setSelectedComp] = useState("");
const changeLanguage = (value) => {
setSelectedComp(value);
};
<RNPickerSelect
placeholder={{ label: i18n.t("SET_LANGUAGE") }}
style={pickerSelectStyles}
onValueChange={(value) => changeLanguage(value)}
items={companyName}
doneText={"בוצע"}
value={selectedComp}
useNativeAndroidPickerStyle={false}
fixAndroidTouchableBug={true}
/>
i want the names for the dropdown list coming from array of object list like below one.
טרגט
קוסל
מעיין
מעיין תיכונים
משרד החינוך
מ.החינוך אולפני
חינוך התישבותי
לא לגעת -חברת הדגמה
How can i add name from array list for dropdown list?
According to the official react-native-picker-select documentation, the data you want to display in the dropdown, should have the keyword label, but you are trying to display name keyword.
The items for the component to render
Each item should be in the following format: {label: 'Orange', value: 'orange', key: 'orange', color: 'orange', inputLabel:
'Orange!'}
label and value are required
Something like this:
<RNPickerSelect
onValueChange={(value) => console.log(value)}
useNativeAndroidPickerStyle={false}
placeholder={{ label: "Select your favourite language", value: null }}
items={[
{ label: "JavaScript", value: "JavaScript" },
{ label: "TypeStript", value: "TypeStript" },
{ label: "Python", value: "Python" },
{ label: "Java", value: "Java" },
{ label: "C++", value: "C++" },
{ label: "C", value: "C" },
]}
/>
I use Axios to display a JSON data and I have succeeded. But I want to show an object based on date and time, it shows now all data and I need to filter it.
So I want to look at today's date and show the object based on that, so I want to show the next upcoming event. (24/05/2020)
What I currently have:
Json:
{
"doc": [
{
"data": {
"events": {
"18807612": {
"_dt": {
"_doc": "time",
"time": "18:45",
"date": "14/05/20",
"tz": "UTC",
"tzoffset": 0,
"uts": 1566067500
},
"week": 33,
"teams": {
"home": {
"name": "name 1",
"mediumname": "name1",
"uid": 3014
},
"away": {
"name": "name 2",
"mediumname": "name 2",
"uid": 3020
}
}
},
"18807618": {
"_dt": {
"_doc": "time",
"time": "18:45",
"date": "24/05/20",
"tz": "UTC",
"tzoffset": 0,
"uts": 1566067500
},
"week": 33,
"teams": {
"home": {
"name": "name 1",
"mediumname": "name1",
"uid": 3014
},
"away": {
"name": "name 2",
"mediumname": "name2",
"uid": 3020
}
}
}
}
}
}
]
}
Store:
async loadPosts({ commit }) {
// Define urls pages
const urlEvents = 'http://api.example.com/302020';
// Set pages
const [
responseEvents
] = await Promise.all([
// Responses pages
this.$axios.get(urlEvents)
]);
// variables pages
this.events = responseEvents.data.doc[0].data.events
// mutations pages
commit('SET_EVENTS', this.events)
}
},
mutations: {
SET_EVENTS (state, events) {
state.events = events;
}
}
And to show the data I use this:
import {mapState} from 'vuex';
export default {
name: 'NextMatch',
mounted() {
this.$store.dispatch('loadPosts')
},
computed: {
...mapState([
'events'
])
}
}
<h1>{{events}}</h1>
But this shows all data, and what I try to get is the first upcoming event for the object with the "uid": 3014.
So I want to show the date, time and names of the home and away team.
How can I get the correct data by filtering the data?
Something like this or similar to this should work:
In your Vue component's <template>:
`<h1>{{selectedEvent._dt.date}}</h1>`
In your Vue component's <script>:
props: {
eventID: {
type: Number,
default: 3014
},
},
computed: {
...mapState([
'events'
]),
eventsArr(){
if (!this.events) return {} //make sure Object.entries gets object.
return Object.entries(this.events)
},
selectedEvent(){
const selectedArr = this.eventsArr.find(([eID, e]) => e.teams.home.uid === this.eventID)
return selectedArr[1]
}
}
I have a State with editedIndex i want to change it in forEach loop but i am not able to call it in that loop.
i have done this code so far
data() {
return {
dialog: false,
comments: [],
editedReply: {
reply: null,
comment_id: null,
name: JSON.parse(localStorage.getItem("user")).name,
email: JSON.parse(localStorage.getItem("user")).email
},
editedIndex: -1
};
},
in above code i have added the initial state of comments which contains index of all comments
I am trying to update the replies of each comment.
handleEdit(reply) {
let commentArray = this.comments;
commentArray.forEach(function(comment) {
comment.reply.forEach(function(item) {
if (reply.id === item.id) {
this.editedIndex = comment.reply.indexOf(item);
this.editedReply = Object.assign({}, item);
}
});
});
this.dialog = true;
},
from i have the list of comments in this.comments and reply represents the reply on which i have clicked to update.
my problem here is i am not able to call this.editedIndex and this.editedReply in if condition as i have mentioned above.
I have used comment.reply every comment contains a array of reply which you can see in below json data for comment i want to update the this json reply
json data for my comments is
{
"comments": [
{
"id": 5,
"comment": "nice blog",
"name": "test user",
"email": "dhruvil#gkmit.co",
"status": true,
"created_at": "2020-05-28T04:36:46.797Z",
"article": {
"id": 308,
"title": "test for comment article"
},
"reply": [
{
"id": 99,
"reply": "abcbc",
"name": "test2",
"email": "test2#mailinator.com",
"created_at": "2020-05-29T13:23:31.358Z"
},
{
"id": 100,
"reply": "abcbc",
"name": "test2",
"email": "test2#mailinator.com",
"created_at": "2020-05-29T13:23:31.521Z"
},
]
},
{
.......... and so on
},
]
}
Try using this snippet for handleEdit method:
handleEdit(reply) {
let commentArray = this.comments;
commentArray.forEach(comment => {
comment.reply.forEach(item => {
if (reply.id === item.id) {
this.editedIndex = comment.reply.indexOf(item);
this.editedReply = Object.assign({}, item);
}
});
});
this.dialog = true;
},
What's different here is I used arrow functions for the callbacks of forEach operations.
first question here.
when i try to run this, it does fetch data in the response.data, but that data is not set into state to be passed through as prop to another page and it always stays [Object object] or [undefined] & i have no clue what's going wrong
state = {
APiData: {},
userInput: "cheese",
onCall: false
}
findFood = () => {
let self = this;
let userInput = this.state.userInput.toLowerCase();
let url = "https://api.spoonacular.com/recipes/search?query=" + userInput + "&number=1&apiKey="+apiKey;
axios.get(url)
.then(function (response) {
console.log(response.data); //get's data
self.setState({APIdata: response.data});
})
.catch(function (error) {
console.log(error)
});
}
renderbody = () => {
console.log(this.state.APIdata) //this thing, is undefined
// return (<SearchBody data={this.state.APIdata} key={apiKey}/>)
}
this is the data in response.data
"baseUri": "https://spoonacular.com/recipeImages/",
"expires": 1585843318293,
"isStale": false,
"number": 1,
"offset": 0,
"processingTimeMs": 437,
"results": Array [
Object {
"id": 215435,
"image": "three-cheese-pizza-for-cheese-lovers-215435.jpg",
"imageUrls": Array [
"three-cheese-pizza-for-cheese-lovers-215435.jpg",
],
"readyInMinutes": 45,
"servings": 8,
"title": "Three-Cheese Pizza (For Cheese Lovers)",
},
],
"totalResults": 855,
}
Object {
"baseUri": "https://spoonacular.com/recipeImages/",
"expires": 1585843318293,
"isStale": false,
"number": 1,
"offset": 0,
"processingTimeMs": 437,
"results": Array [
Object {
"id": 215435,
"image": "three-cheese-pizza-for-cheese-lovers-215435.jpg",
"imageUrls": Array [
"three-cheese-pizza-for-cheese-lovers-215435.jpg",
],
"readyInMinutes": 45,
"servings": 8,
"title": "Three-Cheese Pizza (For Cheese Lovers)",
},
],
"totalResults": 855,
}
You are not using state. Your state needs to be inside your constructor
constructor(props) {
super(props);
this.state = {
APiData: {},
userInput: "cheese",
onCall: false
}
}
Then, you just need to call this.setState({ APIdata: response.data });
I would recommend you to use react-redux to get data using this.props.
I've implemented autocomplete for my address field, but the json returned from the Google Maps Places Autocomplete doesn't include the geocoded coords for the places.
There are some answers out there that don't seem to fit. For instance, this one refers to things like google.maps.places.Autocomplete(input, options); which I don't think is a thing in React Native.
Other answers appear to be based on react-native-google-places-autocomplete, but I've implemented this myself and I'd love to not do it again using that module.
Here's my method where I call the API.
async handleAddressChange() {
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleAPIKey}&input=${this.state.address}`;
try {
const result = await fetch(url);
const json = await result.json();
this.setState({ addressPredictions: json.predictions });
} catch (err) {
console.error(err);
}
}
setAddress(prediction) {
this.setState({ address: prediction.description, showPredictions: false });
}
The API response doesn't have any place or geometry property on it:
Object {
"description": "1234 Some Avenue Northeast, Washington, DC, USA",
"id": "4c79fba1b3a5ad33478b79b54896a75a4d56ca53",
"matched_substrings": Array [
Object {
"length": 4,
"offset": 0,
},
],
"place_id": "ChIJneQ1fBO5t4kRf8mTw4ieb4Q",
"reference": "ChIJneQ1fBO5t4kRf8mTw4ieb4Q",
"structured_formatting": Object {
"main_text": "1234 Some Avenue Northeast",
"main_text_matched_substrings": Array [
Object {
"length": 4,
"offset": 0,
},
],
"secondary_text": "Washington, DC, USA",
},
"terms": Array [
Object {
"offset": 0,
"value": "1600",
},
Object {
"offset": 5,
"value": "Maryland Avenue Northeast",
},
Object {
"offset": 32,
"value": "Washington",
},
Object {
"offset": 44,
"value": "DC",
},
Object {
"offset": 48,
"value": "USA",
},
],
"types": Array [
"street_address",
"geocode",
],
}
I have found a solution for the same-
Just use like this-
<GooglePlacesAutocomplete
GooglePlacesDetailsQuery={{ fields: "geometry" }}
fetchDetails={true} // you need this to fetch the details object onPress
placeholder="Search"
query={{
key: "API_KEY_GOES_HERE",
language: "en", // language of the results
}}
onPress={(data: any, details: any = null) => {
console.log("data", data);
console.log("details", details);
console.log(JSON.stringify(details?.geometry?.location));
}}
onFail={(error) => console.error(error)} />
Once you have the place id (ChIJneQ1fBO5t4kRf8mTw4ieb4Q for the example in your question), you can do a place details request.
Make sure you include the Places library in your API call: https://maps.googleapis.com/maps/api/js?libraries=places and a valid API key.
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(0, 0),
zoom: 15
});
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJneQ1fBO5t4kRf8mTw4ieb4Q'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
// Create marker
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
// Center map on place location
map.setCenter(place.geometry.location);
}
});
}
initialize();
#map-canvas {
height: 160px;
}
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initialize">
</script>