How to destructure a Json array object to use in my react component? - json

I have sent a http get request and have received an JSON object as follows:
How can I destructure the json array and convert it into an array in my react component?

Alright, do you have an array of objects. It's no big deal my friend, you extract it on both of this ways, choose the one that fits your needs.
1st way, extracting only elements:
const [element1, element2, element3, ...rest] = carpak;
This way you will extract the three first elements to the variables above and the rest of the array will be placed in the variable rest.
2nd way, extracting properties of the elements in array:
const [{
id: id1,
latitude: la1,
longitude: lo1,
...rest: rest1,
}, {
id: id2,
latitude: la2,
longitude: lo2,
...rest: rest2,
}] = carpak;
In this example we accessed the first and the second element's properties. But we didn't care about the rest of the array of elements. Note that we are using some alias for the variables because if we don't do so, the variables would be used twice and we would have a compilation problem.
3rd way, extracting elements and properties from array:
const [{
id,
latitude,
longitude,
...restProperties,
}, element2, ...restElements] = carpak;
Now we have accessed the first element's properties, the entire second element and the rest of the elements in the array. Now we don't need aliases because we are only using the variables once.
Hope any of these help you man. In addition I would like to recommend you the next two links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

Related

How to take some data from an object?

I have to put data from json file to my reducer.
And after mapping this file I got an object which includes data that I need.
export const datas = data.properties.map(data => (<store key={Math.floor(Math.random()*1234)} author={data.value} comment={data.group} rate={data.type} />));
this is console log, I just need props from this
How to get just normall react-table, not an object which is not accepting by reducer state?
Or how to implement it to reducer state to get effect that I need?
I am sorry for stupid questions, I hope you will help me :)
The code which you posted takes an array of objects from a variable data.properties and maps them to an array of JSX elements created by the component store. Perhaps it is better readable with line breaks.
export const datas = data.properties.map(
data => (
<store
key={Math.floor(Math.random() * 1234)}
author={data.value}
comment={data.group}
rate={data.type}
/>
)
);
Your console.log of datas shows that array of React JSX element instances. In your array you have 5 objects which are each a JSX element ($$typeof: Symbol(react.element)) with type: "store" (the component type), the numeric key that you created for this element, and a props object which contains all of the props that you passed: author, comment, and rate (key is a special prop so it is not included here).
You are asking to just create an object with the props rather than creating a store element. We want to take the array data.properties and use the .map() method to map it to this props object.
The variable name that you use inside of your .map() callback can be anything, but as a best practice I recommend that you should not use the variable name data again. Reusing a name is called variable shadowing and it won't cause errors, but it can make your code very confusing. I will call it datum instead.
Here is the code that you want:
export const propsArray = data.properties.map(
datum => ({
key: Math.floor(Math.random() * 1234),
author: datum.value,
comment: datum.group,
rate: datum.type,
})
);

Immutable JS duplicate / copy List within Map

I have an Immutable Map like this
Immutable.fromJS({
sortingOnFields: false,
items: [],
selectedItems: [],
columnsConfigs: {
meta: {},
columns: {}
},
});
how do I copy the items List to selectedItems list.
This return state.set('selectedItems', state.get('items'));
doesn't do the job correctly as later if I do
props.listing.get('selectedItems').includes(Immutable.fromJS(item));
where Immutable.fromJS(item) is from the 'items' List, it returns false.
I tried this which works but looks a bit too much
return state.set('selectedItems', Immutable.fromJS(state.get('items').toJS()));
any ideas of a better solution?
The problem is with your test. You are successfully setting the same List at both keys. You're retrieving the value at items, which is a List, and you're setting that exact same List as the value at selectedItems.
Even though that is working, your test isn't doing its job. You wrote:
props.listing.get('selectedItems').includes(Immutable.fromJS(item));
That line says: Get the List at selectedItems. Now create a brand new Immutable object using the fromJS method. Does the List at selectedItems contain that new Immutable object? The answer is no, because you just created that item from scratch, so it is definitely not contained in the List at selectedItems.
If each item is a primitive value, you can just check like this:
props.listing.get('selectedItems').includes(item);
If each item is a object, then did you convert it to an Immutable object? If not, then you can pass in a reference to the item, as above. If you did convert it to an Immutable object, make sure you pass a reference to the correct Immutable equivalent to the includes method.

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

Filter Properties Inside Array of Objects to Properly Display Axes in Parallel Coordinate d3

I am creating a parallel coordinate plot from a csv file. There are a few columns in my csv file that I need for other parts of my script (e.g., ID column to join csv to topojson; StateName so that I know which state's data to display).
Here are the properties for each object in my array:
CVIRISK, ERR_M_YR, FID, FULLSTATE, GEOM, LENGTH
I can create my parallel coordinate plot properly with the values for each of these properties drawing for every record in my csv.
The problem is that I don't want FID, FULLSTATE or LENGTH to have an axis and show up in my PCP.
I want to create a new array of objects that has all the same objects with specific properties removed.
If source is the array of objects with all the props, and you want picked to be an array of objects with some of those props, you can use Array.prototype.map to instantiate new objects with just the props you care about:
var picked = source.map(function(d) {
return {
CVIRISK: d.CVIRISK,
ERR_M_YR: d.ERR_M_YR
};
});

Get value of json string

[
{
"type": "spline",
"name": "W dor\u0119czeniu",
"color": "rgba(128,179,236,1)",
"mystring": 599,
"data": ...
}
]
I am trying to access this json as json['W doręczeniu']['mysting'], and I get no value why is that?
You're trying to access the index "W doręczeniu" but that's not an index it's a value. Also, what you seem to have is an array of JSON objects.
The [ at the start marks the array, the first element of which is your JSON object. The JSON obj begins with the {
You're also trying to use a [ ], but JSON values are accessed with the dot operator.
I'm not sure which index you're actually trying to access, but try something like this:
var x = json[0].mystring;
The value of "W doręczeniu" is not a key, so you cannot use it to get a value. Since your json string is an array you'll have to do json[0].nameto access the first (and only) element in the array, which happens to be the object. Of course, this is assuming json is the variable you store the array into.
var json = [{"type":"spline","name":"W dor\u0119czeniu","color":"rgba(128,179,236,1)","mystring":599}];
console.log(json[0].mystring); //should give you what you want.
EDIT:
To get the last element in a js array, you can simply do this:
console.log( json[json.length -1].mystring ); // same output as the previous example
'length - 1' because js arrays are indexed at 0. There's probably a million and one ways to dynamically get the array element you want, which are out of the scope of this question.