Get first object from array of objects in react [duplicate] - reactjs

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 4 years ago.
I am trying to get the first object from an array of objects. Fetched data in componentDidMount and return:
var array1 = [
{
Id: 1,
Categories: 200
},
{
Id: 2,
Categories: 100
}
]
(real data is much more complicated but in the same format)
What I want is this:
array2 = [
Id: 1,
Categories: 200
]
I was using
var iterator1 = array1.entries();
let array2 = iterator1.next().value
and when I console.log(array2) it shows the array data (all key and value is in index 1 of array), then when I console.log(array2[1].Id)
it shows undefined right inside the render method in class component. I use the same code in other IDE but not using react the code work. Could someone explain to me please? Appreciate for any help.
Edit:
At the end I found that I asked the wrong question. I failed to get the data because I declared the data in my reducer to object instead of array. I mark the answer by larz since you just need to put index 0 to get the first object from the array of objects.

Grab the first item in your array using [0], which returns an object in your case. Then you can call .Id on it to get the id.
var array1 = [
{
Id: 1,
Categories: 200
},
{
Id: 2,
Categories: 100
}
];
var first = array1[0];
console.log(first, first.Id);

Related

Creating a data structure that will hold objects in React

I'm building a program in React that is basically a questionnaire / survey, so far I've got users answering a bunch of questions then what I am trying to do is take the answers, filter them a bit then return an object to store using Redux. Each question is an object it self that holds different factors than I am trying to measure. Although, I'm getting stuck with actually trying to create the structure of the final object.
I want the object to look something like this:
Results {
Question1 {
factor1: 1,
factor2: 2,
factor3: 3
},
Question2 {
factor1: 3,
factor2: 6
},
and so on...
}
But when I try create create it by saying for example
let results = {
Question1 {
factor1: 0
}
}
React doesn't like it. As soon as I try nest another object inside it returns an error.. Am I missing something simple or do I need to try another approach, any help would be appreciated
It should be like this, property and value needs to be separated by a :
let results = {
Question1 :{
factor1: 0
}
}
let Results= {
Question1: {
factor1: 1,
factor2: 2,
factor3: 3
},
Question2: {
factor1: 3,
factor2: 6
},
and so on...
}

Swift filter object array wit another object array

i struggle my had now sine several days with a way to do conditional filter of an object array with another object array.
lack on capabilities to properly abstract here... maybe you ahve some ideas.
I have a given Object Array A but more complex
var ArrA = [{
number: 1,
name: "A"
}, {
number: 2,
name: "C"
}]
And i want to filer for all results matiching id of Object Array B
var ArrB = [{
id: 1,
categorie: "wine"
}, {
id: 3,
categorie: "beer"
}, {
id: 10,
categorie: "juice"
}]
And in the best case moving this directly also together with an if condition.... but i was not able to handle it ... here is where i am now ... which is not working....
let newArray = ArrA.filter{$0.number == ArrB.... }.
if (newArray.count != 0){
// Do something
}
is there a lean way to compare one attribute of every object in an array with one attribute of another every object in an array ?
Lets break this down: You need all arrA objects that matches arrB ids, so first thing first you need to map your arrB to a list of id (because you dont need the other infos)
let arrBid = Set(arrB.map({ $0.id })) // [1, 3, 10]
As commented below, casting it to Set will give you better results for huge arrays but is not mandatory though
Then you just need to filter your first arrA by only keeping object that id is contained into arrBid :
let arrAFilter = arrA.filter({ arrBid.contains($0.number) })
[(number: 1, name: "A")]
and voila

Array .map() returning undefined

This is the structure of the array when I console.log it.
-[]
-0: Array(31)
-0:
-date: "2018-08-26T00:00:00-04:00"
-registered:
-standard: 0
-vip: 0
-waitlisted:
-standard: 0
-vip: 0
This is my code to map the date and the registered (two separate arrays):
this.data.map((value) => value.date);
this.data.map((value) => value.registered['standard']);
I either get an empty array or undefined when I log these. What am I doing wrong?
I want to use these for a chart using ChartJS where:
this.lineChart = new Chart(lineCtx, {
type: 'line',
data: {
datasets: [{
label: (I want the dates to be the labels),
data: (I want the list of standard registrants)
}]...
EDIT:
I've updated the way I get the data to show the following structure:
{
"registrationHistory": [{
"date": "2018-08-26T00:00:00-4:00",
"registered": {
"vip":0,
"standard":0
},
"waitlisted":{
"vip":0,
"standard":0
}
{
,...
}
]}
Your array is two-dimensional and map is iterating only the first dimension, i.e:
-[]
-0: Array(31) // first dimension
-0: // second dimension
-date: "2018-08-26T00:00:00-04:00"
...
This would look like the following JSON string:
[[{"date":"2018-08-26T00:00:00-04:00", ...}]]
Since you haven't provided a full example it's impossible to recommend the most applicable solution:
If you control the data source, remove the first dimension since it appears redundant.
Assuming you only want the first element of the first dimension, refer to that key:
this.data[0].map((value) => value.date);
If your data model is more complex than revealed in your question you'll need to figure out another approach.

How to iterate item inside an array of objects from req.body? [duplicate]

This question already has answers here:
Mongoose validation error but I put documents correctly
(2 answers)
Closed 6 years ago.
I have this variable that I needed to fill up using request body
var orderItem = {
userPurchased: body.userPurchased,
products:[{
product: body.products.product,
size: body.products.size,
quantity: body.products.quantity,
subTotal: body.products.subTotal
}],
totalQuantity: body.totalQuantity,
totalPrice: body.totalPrice,
otherShipAd: body.otherShipAd,
modeOfPayment: body.modeOfPayment
};
Here is my request body looks like.
The problem here is that the request body is an array of objects and if I access it in the way I shown on top, it would be undefined. If I put the number of the array like body.products.product[0], all the records will be the same.
Can anyone tell me how to iterate all the products and put it inside the variable?
Not sure if I've understood what your dilemma is but from the fact that your destination object appears to have the exact same schema as your source, why don't you just assign that value to your var?
var orderItem = request.body;
Let's say you still had some reason to need to create that copy of the array from request.body? This would still be just a one-liner to assign the request.body array to your target variable:
var orderItem = {
userPurchased: body.userPurchased,
products: body.products,
totalQuantity: body.totalQuantity,
totalPrice: body.totalPrice,
otherShipAd: body.otherShipAd,
modeOfPayment: body.modeOfPayment
};
according to your console response
you should use:
var product;
for(var i=0; i< body.products.length;i++)
{ product = [];
product[product] =body.products[i].product[0];
// set all properties
}
orderItem.products.push(product);

Jade variable from array // not working

I'm passing an array to the jade document. Then I'd like to access the values of the array via a variable to keep the markup simple. Just see the example below. I have already picked up, that the jade syntax can be quite strange dealing with arrays (stuff like "arr.[0]"). Can you guys tell me what im overseeing here? Big thanks!
- var arr = [
{
name: 'foo',
id: 1
},
{
name: 'bar',
id: 2
}
]
- var item = arr[0];
h2 #{item.id} // doesn't work
h2 #{arr[0].id} // works
h2 #{arr[0].id}
Works because you are referencing the id for arr item in the '0' (first) position. This is because the array starts counting things with a zero, not a one.
As you can probably see from your results, this code would return '1', which means that you could expect h2 #{arr[0].name} To return 'foo'.
To get the ids from both items in the array 'arr', change your code to this.
h2 #{arr[0].id}
h2 #{arr[1].id}

Resources