I don't know how to remove the nested array in react native. Example :
Array [
Array [
Array [
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
Array [
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
],
]
What I want is just this array structure :
Array [
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
Array [
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
This is my code for pushing into the array :
for (let menu of response.data.Data) {
apiChartingMenu = new ApiChartingMenuModel (
menu.idx,
menu.shortDescription,
menu.titlecommand,
menu.command,
menu.commandtype,
);
data.push(Object.values(apiChartingMenu));
}
How can I achieve this?
You can use plain Javascript by using array.flat(). For your case this could be done as follows.
array = [
[
[
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
[
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
]
]
console.log(array.flat())
In your case you could make it work by either using
data.push(Object.values(apiChartingMenu).flat());
or by not introducing the object ApiChartingMenuModel at all, since you are just using its values anyway. This could also be done as follows.
// dummy menu object
menu = {
idx: 77,
shortDescription: "description",
titlecommand: undefined,
command: undefined,
commandtype: undefined
}
data = []
data.push([menu.idx, menu.shortDescription, menu.titlecommand, menu.command, menu.commandtype])
console.log(data)
Related
I working in a form who generate fields dynamically using formik with the <FieldArray />that acts as a functional component.
So, I have this object to send on submit to my backend:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "",
"propsTwo": "",
"view": 0,
}
]
}
],
"typeOptions": []
}
As you can see, I have two arrays to working in this json object, one is Tapes who has Elements to work together and typeOptions who has values to send. My proposal is to send in a form with dynamic fields to my backend when whenever the user add new tapes and add new field props which will be rendered later in a mobile app.
Assuming the user added two new tapes and added two new elements for each one, the result of this json would be this:
{
"tapes": [
{
"name": "TapeOne",
"elements": [
{
"propsOne": one,
"propsTwo": two,
"view": 0,
},
{
"propsOne": 1,
"propsTwo": 2,
"view": 0,
}
]
},
{
"name": "TapeTwo",
"elements": [
{
"propsOne": one,
"propsTwo": two,
"view": 0,
},
{
"propsOne": 1,
"propsTwo": 2,
"view": 0,
}
]
}
],
"typeOptions": []
}
Well, so far so good, I can form a dynamic generation of Tapes and Elements according to the user's request, but there is a moment when the user asks for an option selector and the value I get in Elements is in the View, where number by the value of 1 is required.
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "",
"propsTwo": "",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": []
}
]
}
It is at this point that I need to retrieve the values that it passes on in these fields that will be dynamically generated and insert them into a new array that is called typeOptions in its values, the flow being like this:
The user will ask for a field who has multiple fields, like a selector.
This field will be generated in Tapes, Elements with the value being assigned to view with 1
The user will pass the values in these fields and they will be placed in typeOptions.values
So, the user add this new field and when this happens, I need pass the values that will be passed on fields will be generated for him.
The result needs be like this:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "One",
"propsTwo": "Two",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": ["ValueOne", "ValueTwo", "ValueThree"]
}
]
}
Or when two Elements has the same view like 1:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "One",
"propsTwo": "Two",
"view": 1,
},
{
"propsOne": "1",
"propsTwo": "2",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": ["ValueOne", "ValueTwo", "ValueThree"]
},
{
"values": ["Value1", "Value2", "Value3"]
}
]
}
I've already tried to use two <FieldArray /> having one inside the other, as I already do for Tapes and Elements, because with this I could use the map function to get the view value and add a conditional to permeate two new <FieldArray /> to add the values not only for each object selected inside the typeOptions, but also for each value that is inserted together.
What is the best way and best practice to do this?
my question is above and I am trying like for 45mins to extract the value under "distance" below, but I fail at every try. I hope you guys can help me.
{
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
So I need the value under rows --> elements --> distance then value. I tried something like this in JavaScript:
var payload = JSON.parse(body)
console.log(payload.rows["elements"].distance.value)
Thanks! :)
Süleyman Demir
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (object_name.property_name). You can access an array's element by typing the element index in square brackets next to the array's name (array_name[element_number]).
In our case we access the property "rows" which is an array of the object "payload" - payload.rows. Then we access the element number [0] of this array by typing [0] next to the property's name - payload.rows[0]. We get another object which has the property "elements" in it - payload.rows[0].elements . This property stores another array and we access its first element again -
payload.rows[0].elements[0]. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - payload.rows[0].elements[0].distance.value
Source https://eloquentjavascript.net/04_data.html
Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
Try like below
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
I don't know exactly what you want, but you can get the distance object with something like that:
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped!
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
So I need to add sort functionality to the fuel.name value inside this array...
const orders = [
{
"_id":"5d14a31490fb1e0012a3d2d8-1",
"orderId":"0JL5ORM0JT-1",
"created":"2019-06-27T11:05:56.377Z",
"createdDate":"2019-06-27T09:05:56.377Z",
"offers":[
{
"price":95.27,
"fuel":{
"_id":"5ce13948eaef5200113b0de8",
"name":"Diesel B7",
"description":"Diesel",
"lpt":0,
"duty":0,
"type":"SPOT",
"created":"2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Petrol",
"description": "Petrol",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Fossil Fuel",
"description": "Fossil Fuel",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
},
}
]
}
]
I want the "offers" object to reorder based on the "fuel.name"
orders.sort((a: any, b: any) => a.offers[0].fuel.name.toUpperCase().localCompare(b.offers[0].fuel.name))
When I console log the above it just return the data in the same order. I have set up a fiddle below to replicate the issue I am having.
Here is a fiddle
You are currently sorting the orders array based on the first item inside offers array. Instead, you should sort each object's offers array inside the orders
const orders=[{_id:"5d14a31490fb1e0012a3d2d8-1",orderId:"0JL5ORM0JT-1",created:"2019-06-27T11:05:56.377Z",createdDate:"2019-06-27T09:05:56.377Z",offers:[{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Diesel B7",description:"Diesel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Petrol",description:"Petrol",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Fossil Fuel",description:"Fossil Fuel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"},}]}];
orders.forEach(o =>
o.offers.sort((a, b) => a.fuel.name.localeCompare(b.fuel.name))
);
console.log(orders)
I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!
For sake of easierness of typing so my return from twitter api looks like this
[id:1
connections: "NONE"
],
[id:2
connections: ["following", "followed_by"]
]
What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!
The twitter api docs show an examples json as
[
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
]
Can any point me in the correct direction?, how do I find out if following exists?
Thanks
connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():
var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1
So to check if "following" is in the array:
if (connections.indexOf("following") !== -1) {
// yeah!
} else {
// doh!
}
To count the objects in your example which have "following":
var o = [
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
];
var withFollowing = o.filter(
function (i) {
return i.connections.indexOf("following") !== -1;
}
);
// filter() returns a new array
// this new array has only the elements for which the function returns true
console.log(withFollowing.lenght);
I want to feed a dijit.form.Select (Dojo Select-Box) with a Data-Store (JsonRest). The Problem is, that the JSON-Parser only accepts JSON in this format:
[
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
];
The REST-API of the webapplication we want to call delivers the following JSON:
{
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
That is why the Select Box does not show any data. Therefore, we need to remove the {"data": part and the last part of the JSON message bevore passing it to the Dojo Select Box.
The Data is stored in a JsonRest Object. So the question is how we can remove the first and the last part of the JSON in a way that simply this here is given to the Select-Box:
[
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
];
Thank you for your answers and best regards
Ben
Create a new Array variable from the data for the dojo select seems simplest ...
var restapidataObj = {
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
var dojoSelectArray = restapidataObj.data;
Now pass dojoSelectArray to dojo
Store the result in a object and access the data property of that object.
var result = {
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
result.data would give you the data array.
Check the javascript object documentation at MDN
resultFromServer =
{
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
this convert to object (Use this incase resultFromServer is a string)
var Output = eval('('+ resultFromServer+')')
this gives your output
JSON.stringify(Output.data)
gives the string
"[{"id":"1","name":"One1"},{"id":"2","name":"Two1"}]"