ReactJS ES6 array filtering - arrays

I'm trying to group data from an object to a multidimensional array
In the last three days I've tried multiple ways to get the result I want. Since I've no luck, probably because of my poor knowledge of ReactJS/ES6. I hope someone can explain how I can get this to work.
I think I'll have to use the map function. Within the map function, a filter function to get the unique companies and then a loop to add the table information.
The end result should be like this: https://wireframe.cc/No5uB7
The data I'd like to filter:
{
"viewings": [
{
"companyXXX": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"companyXXX": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"companyYYY": "company-YYY",
"rejection": 40,
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
The code I still have that isn't working
genData(data) {
const di = data.viewings;
let mps = [];
di.map(m => mps.push(m.company));
mps = Array.from(new Set(mps));
console.log( mps );
let mps = [];
di.map((m) =>
console.log( di.filter(mps => m.company) )
);
}

I might help if your input data was a bit more consistent, especially since you're trying to write m.company, which won't mean anything unless there is a company object in each viewing.
{
"viewings": [
{
"company": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"company": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"company": "company-YYY",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
Then you can write:
var viewings = data.viewings.
var firstViewing = viewings[0];
var firstCompany = firstViewing.company;
var firstTimeStart = firstViewing.time_start;
// etc...
Your input data should be more structured to begin with.
Then you can log out each company name:
var viewings = data.viewings;
viewings.forEach(v => {
console.log(v.company);
});
You mention JSX in your question, but there's no JSX code. This appears to be an issue with your knowledge of JS rather than JSX.

Related

array with objects containing array

Sorry guys if my way of asking the question in the title is not correct.
I am working on a project on react js and I am getting the data like this
[
{
"count": [
{
"1": 16
},
{
"1": 149
}
],
"day": "2019-08-27"
}
]
now this is my first time I am dealing with this kind of data and I really have no idea how can I show it like this I am really sorry guys I literally can't even show what I have tried because it does not seem relevant
[
{
count: 165
day:"2019-08-27"
}
}
Assuming the data you're getting is under a variable called data you could use reduce:
The below makes the assumption the count is always an array of objects with just 1 key called '1'.
const newData = data.map(datum => {
datum.count = datum.count.reduce((count, item) => {
return count + item['1']
}, 0)
return datum
})
You can try something like this:
let arr = [
// item
{
count: [
{
"1": 16
},
{
"1": 149
}
],
day: "2019-08-27"
}
];
arr.map(item => {
Object.keys(item).map(key => {
console.log(item[key])
// if item[key] is iterable
if(Array.isArray(item[key])) {
item[key].map(val => {
console.log(item)
})
} else {
console.log(item[key])
}
});
});
The concept is that for Objects you do a Object.keys().something and for an array you do a arr.map(item => ...)

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

How to fetch data from json using Reactjs

I know this is very basic. but i would appreciate if anyone can help me understanding on how to fetch data from json using React js.
I have just started to learn React so was just curious to know if there are any ways to fetch data from complex json using this.
I have tried to follow React Tutorial
I am trying to fetch data from 2nd level keys in a json. I was able to do that using Object.keys, but I am not sure what the issue is here when i am trying to apply it to my dataset. I am just unable to get anything when i try the commented dataset which is not that different from the other dataset. Can Object.keys be applied to datasets where there are more than one key? Can anyone please help?
Please check my fiddle
Here is my code
var SearchStock = React.createClass({
getInitialState: function() {
return {searchString: ''};
},
handleChange: function(e) {
this.setState({searchString: e.target.value});
},
render: function() {
var stocks = this.props.items, searchString = this.state.searchString.trim().toLowerCase();
if (searchString.length > 0) {
stocks = stocks.filter(function(l) {
// return l.name.toLowerCase().match(searchString);
return l[Object.keys(l)[0]]["name"].toLowerCase().match(searchString);
});
}
return <div >
< input type = "text" value = {this.state.searchString} onChange = {this.handleChange} placeholder = "Type here" / >
< ul >
{stocks.map(function(l) {
return <li > {l[Object.keys(l)[0]]["name"]} < /li>
// return <li > {l[Object.keys(l)[0]]["name"]} < /li>
})
}
< /ul>
< /div>;
}
});
// var stocks = [{"F": {"symbol": "F", "name": "Ford Motor", "bidPrice": 13.41, "askPrice": 13.36}}, {"GE": {"symbol": "GE", "name": "General Electric", "bidPrice": 32.33, "askPrice": 32.39}}, {"JNJ: {"symbol": "JNJ", "name": "Johnson \u0026 Johnson", "bidPrice": 121.0, "askPrice": 123.0,}}];
var stocks = [{"symbol": {"symbol": "F", "name": "Ford Motors"}, "name": "Ford Motor", "bidPrice": 13.41, "askPrice": 13.36}, {"symbol": {"symbol": "GE", "name": "General Electronics"}, "name": "General Electric", "bidPrice": 32.33, "askPrice": 32.39}, {"symbol": {"symbol": "JNJ", "name": "Johnson \u0026 Johnson"}, "name": "Johnson \u0026 Johnson", "bidPrice": 121.0, "askPrice": 123.0,}];
ReactDOM.render( < SearchStock items = {stocks} />,document.getElementById('container'));
My Aim is to build a simple single page app in which we can search data from json using the key.symbol, so i am adding another level to the data so that when i build my api i can just put it there using the symbol.
I would appreciate if anyone can help me out with this. Sorry for changing my question in the middle. And thanks for pointing me in the right direction.
implement that in the componentDidMount method of your Stock element.
Something like this:
var Stock = React.createClass({
...
render: function() {
...
},
componentDidMount: function() {
let url = 'myStockApi/' + this.props.symbol;
this.serverRequest = $.get(url, function(result) {
let quote = result;
this.setState({
quote
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
});
Check out the documentation here.
I was able to find my answer from here . I have update my post. Please check the code in my post.

Nesting storing and sorting in struct in angular

Ok, so I have a JSON file with lots of information that can be sorted many ways. The actual JSON is too large, but for a relevant example:
$myData =
{
"id":1,
"author_id":[17],
"date":"10/1/1996",
"title":"Article1"
},
{
"id":2,
"author_id":[16,17],
"date":"9/1/1996",
"title":"Article2"
},
{
"id":3,
"author_id":[16],
"date":"6/1/1996",
"title":"Article3"
};
I want to be able to sort this into a struct with the basic structure like:
$myDataByAuthor =
{"17" =
{
"id":1,
"date":"10/1/1996",
"title":"Article1"
},
{
"id":2,
"date":"9/1/1996",
"title":"Article2"
}
},
{"16" =
{
"id":3,
"date":"6/1/1996",
"title":"Article3"
};
{
"id":2,
"date":"9/1/1996",
"title":"Article2"
}
};
I know the syntax there is bad, but I'm not really sure how to lay this out which is why I'm asking.
The reason I want to do this is because I want to turn around and, using ng-repeat in my code be able to output something to effect of:
Author with id 16
6/1/1996 - Article3
9/1/1996 - Article2
Author with id 17
9/1/1996 - Article2
10/1/1996 - Article1
I'm just not seeing how to get this done.
Thanks!
You can certainly restructure it that way, and here is a fiddle and code of the function that would restructure it that way for you.
var table = {}
myData.forEach(function(element){
element.author_id.forEach(function(id){
table[id] = table[id] || []
table[id].push(element)
})
})
https://jsfiddle.net/q40yhhko/
Considering your data is:
$myData = [{ "id":1, "author_id":[17], "date":"10/1/1996", "title":"Article1"},
{"id":2, "author_id":[16,17], "date":"9/1/1996", "title":"Article2"},
{"id":3, "author_id":[16], "date":"6/1/1996", "title":"Article3" }];
To form the required JSON use below code
$scope.requiredJSON = {}; //FORMATED JSON DATA
angular.foreach($myData, function(value, index){
angular.foreach(value.author_id, function(innerVal, innerIndex){
$scope.requiredJSON[innerVal] = $scope.requiredJSON[innerVal] || [];
$scope.requiredJSON[innerVal].push({id: value.id, date: value.date, title: value.title});
})
});
Following is the output:
{17: [{"id":1, "date":"10/1/1996", "title":"Article1" },
{"id":2, "date":"9/1/1996", "title":"Article2" }],
16: [{"id":2, "date":"9/1/1996", "title":"Article2" }]};
https://jsfiddle.net/AmitParrikar/uzv2p72b/2/

How to push some data from Json into new array in AngularJS?

Let's say I have this Json ..
{
"name": "Mark",
"gender": "male",
"account1": {
"accountNo": 1201,
"balance": 300
},
"account2": {
"accountNo": 1354,
"balance": 5000
}
}
What I expect is like ..
$scope.myArray = [
{
"accountNo": 1201,
"balance": 300
},
{
"accountNo": 1354,
"balance": 5000
}
];
In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).
You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.
Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply
$scope.myArray = json.accounts;
However, as noted, you do not have an accounts array so you need to make one.
var accounts = [];
for(var key in json){
if( !json.hasOwnProperty(key) // skip prototype extensions
|| !json[key].hasOwnProperty("accountNo") //skip non account objects
) continue;
accounts.push(json[key]);
}
And now you may use this array
$scope.myArray = accounts;
You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(foo['account'+i]);
}
Although, this has nothing to do with angularjs.

Resources