I have two arrays. My first array is multidimensional. I am looping over the first array and checking if the index matches HeaderIndex value on an object in my second array. If so I am returning a new array with updated object. However I do not want my returned array to have any undefined values... I tried using array.filter
Here is my code below
const Array1 = [
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink', 'MeowWolf', 'corsair', 'coarse hair'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple', 'purr pull'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange', 'Sears', 'see ears'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]
const Array2 = [{
header: 'First name',
HeaderIndex: 0
},
{
header: 'Last name',
HeaderIndex: 1
},
{
header: 'Company',
HeaderIndex: 2
},
{
header: 'Favorite food',
HeaderIndex: 3
},
{
header: 'Favorite color',
HeaderIndex: 4
},
]
const testResult = Array1.map(
(arr) => arr.map(
(string, index) => {
if (Array2.filter(
(obj) => obj.HeaderIndex === index)[0])
return {
"ChosenHeader": Array2.filter(
(obj) => obj.HeaderIndex === index),
"content": string
}
}))
console.log(testResult);
I am getting this result
0: (8) [{…}, {…}, {…}, {…}, {…}, undefined, undefined, undefined]
1: (6) [{…}, {…}, {…}, {…}, {…}, undefined]
2: (7) [{…}, {…}, {…}, {…}, {…}, undefined, undefined]
3: (5) [{…}, {…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, {…}, {…}]
But I want something like this
0: (5) [{…}, {…}, {…}, {…}, {…}]
1: (5) [{…}, {…}, {…}, {…}, {…}]
2: (5) [{…}, {…}, {…}, {…}, {…}]
3: (5) [{…}, {…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, {…}, {…}]
I guess you need something like this:
const result = array1.map((arr1, index) => {
if (array2.some((arr2) => arr2.HeaderIndex === index))
return {
ChosenHeader: array2.find(obj => obj.HeaderIndex === index),
content: arr1,
};
});
Related
I have this array and it has an array with different number of elements.
var filtered = [Array(3), Array(1), Array(2), Array(7), Array(1), Array(1), Array(5)]
0: Array(3)
0: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
1: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
2: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
1: [{…}] //1 element
2: (2) [{…}, {…}] //2 elements
3: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] //7 elements
I want to access the data inside through looping so I try to use this:
for (i = 0; i < filtered.length-1; i++) {
for (x=0; x<filtered[i].length-1;x++){
let league = document.createElement("div")
league.className = 'league'
league.innerHTML = filtered[i].x.league.name //error occurs on .league.name
parent.appendChild(league)
}}
and I get this error message:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'league')
I likely am referencing it wrong but do not know how else to do this.
import React, { Component } from 'react';
import axios from 'axios';
class Home extends Component {
state = {
responses: [],
scores: [],
values: [],
}
componentDidMount() {
this.fetchQuestionAnswers();
}
fetchQuestionAnswers = () => {
if (this.state.activeSupervisionId) {
axios.get('/question/response/' + this.state.activeSupervisionId).then(res => {
responses: res.data.data, scores: res.data.data.map((s) => s.score), values: res.data.data.map((v) => v.value), loading: false
}).catch(err => console.error(err));
}
}
render() {
console.log(this.state.responses[0].value)
// dot notation not working here under render function but the result of // console.log(this.state.responses[0]) is printed
return (
<div className="pdf-table-container">
<table className="pdf-table">
<thead>
<tr>
<th className="id-col">Id</th>
<th className="text-col">Question</th>
<th className="score-col">Score</th>
<th className="value-col">Value</th>
</tr>
</thead>
<tbody>
<tr className="">
<td className="text-center">1</td>
<td className="text-left">Staff living in the residential quarter</td>
<td className="text-center">{scores[0]}</td>
<td className="text-left">{values[0].staffLivingInQuarter} </td>
</tr>
</tbody>
</table>
</div>
)
}
}
export default Home;
I fetch a data from an API that was sent as array of objects. So lets say I set the state of responses: res.data.data. The result of responses console appear as described below.
(143) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
I will use the 0 index object as an example of data received.
0: {
id: 5,
questionId: 1,
score: "0",
text: "Are there any others",
value: {
designations: {
CCO: { no: "3" },
CDD: { no: "1" },
DSNO: { no: "1" }
},
reaportedStaff: [ "DSNO", "CCO", "CDD" ]
staffLivingInQuarter: "yes"
totalReaportedStaff: 5
}
}
When I console the result of the mapped value I got:
values (143) [{…}, {…}, {…}, 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'yes', 'yes', 'yes', {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', {…}, {…}, 'yes', 'no', 'yes', {…}, {…}, 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', {…}, 'yes', {…}, 'yes', 'yes', 'yes', {…}, 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'yes', 'yes', {…}, 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', {…}, {…}, {…}, {…}, {…}, {…}, 'yes', 'no', 'no', 'yes', …]
In the render function and the returned table I can access the yes and no value. But when I use dot for the object values I got undefined. Meanwhile the dot notation work if console it in the function where I fetched the data.
console.log('values', values[1]) return values {male: '4', child: '6', total: 9, female: '5'}. But if I do values[1].male I got error TypeError: Cannot read properties of undefined (reading 'male')
I'm struggling with how to add the element of the array into an array of objects. I have an array of object:
0: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
1: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
...etc
And I have an array that contains strings:
const titles = ["some title A", "some title B", "some title C"]
So my purpose is, I want to make my data like this:
[
{results: my_existing_array_of_object, title: "some title A"},
{results: my_existing_array_of_object, title: "some title B"},
{results: my_existing_array_of_object, title: "some title C"},
]
How to do that? Thanks in advance
I do some adjustment from the answer of #StepUp
const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
const result = other.map(((o, i) => ({results: o, //add new key
title: (i < titles.length) ? titles[i] : ''})))
console.log(result )
It is possible to use map function to get desired array:
const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
const result = other.map(((o, i) => ({results: o,
title: (i < titles.length) ? titles[i] : ''})))
console.log(result )
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to map over my API to get the nodes.
Here is the format my API is in:
[
{
"agent": "....",
"managementDomain": "...",
"node": "..."
},
{
"agent": "....",
"managementDomain": "...",
"node": "..."
},
...
]
The format I need to get it into for react-select:
const colourOptions = [
{ value: 'orange', label: 'Orange' },
{ value: 'yellow', label: 'Yellow' },
{ value: 'green', label: 'Green' },
];
How I am mapping over it (using Redux for state management):
const alarms = this.props.dataReducer.alarmDetails
const {test} = alarms.map(alarm => ({value:alarm.node, label: alarm.node}))
The error I am getting:
TypeError: Cannot read property 'node' of null
console.log(this.props.dataReducer.alarmDetails)
(288) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, null, {…}, {…}, {…}, {…}, null, {…}, {…}, null, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, null, null, null, {…}, {…}, {…}, {…}, {…}, null, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
0:
agent: "..."
managementDomain: null
node: "..."
What's the best way to map over the API to get the node from each object within the array?
This error is actually self explanatory. Your map code is alright. Problem seem to exist that some of the objects in array is null or empty, so when javascript is trying to find node property on that object, its hitting the rock.
Actually this.props.dataReducer.alarmDetails this data contains null value, something like..
[
{
"agent": "....",
"managementDomain": "...",
"node": "..."
},
{
"agent": "....",
"managementDomain": "...",
"node": "..."
},
null
...
]
So, maybe you can filter the null values:
this.props.dataReducer.alarmDetails.filter(data=>data)
and put map code here
this.props.dataReducer.alarmDetails.filter(data=>data).map(d => ({value:d.node, label: d.node}))
You can return something like this:
import React from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import "./styles.css";
const alarms = [
{ agent: 1, managementDomain: null, node: "node1" },
{ agent: 2, managementDomain: null, node: "node2" }
];
let teamsFromApi = alarms.map(team => { return {value: team.agent, label: team.node} });
function App() {
return (
<div className="App">
<Select options={teamsFromApi} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Note: Replace node data.
You can check the example Codebox
I have 4 arrays full of objects:
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(27) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(21) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Each object contains a bit of information, that I want to display to the viewer:
0: Object { exchange: "NYSE", quote: "JPY", price: "3923.76016", … }
1: Object { exchange: "DEF", quote: "GBP", price: "3924.60972", … }
2: Object { exchange: "FEG", quote: "EUR", price: "3917.31980", … }
3: {…}
exchange: "NEX"
price: "3914.70000"
quote: "USD"
timestamp: "2018-12-31T07:47:11.253Z"
<prototype>: Object { … }
How can I
1) Assign a unique value to the array, ie. Array #1 is VTX, Array #2 is DEF, so that when I display it on the page, I don't need to change the ticker symbol (ie. VTX on exchange NEX is $100, and I only need to change the exchange name and currency/amount)
2) iterate over the arrays to where the iterator moves on to the next object in the array, let's say, every 2-3 seconds?
I'm doing this in React and have passed the data on to props, but now I'm stuck trying to figure this out.
1) You can store all your arrays in on object like this :
const myArrays = [
{
uniqueName: 'VTX',
infos: []
},{
uniqueName: 'DEF',
infos: []
}
]
2) You should store the index in the state, and make it change with setInterval in componentDidMount
componentDidMount() {
this.timerID = setInterval(
() => this.nextInfo(),
1000
);
}