How to create objects dynamically - reactjs

Im working with a library to create tables in react-pdf. And i want to fill it with api data. Is there a way of iterating inside the data{} and create various objects with data from api. Instead of sth like
data={[{firstName: "John", lastName: "Smith",country: "Australia"}]},
data={[{firstName: "Josh", lastName: "Pattison",country: "USA"}]}
have
data={[{firstName: "John", lastName: "Smith",country: "Australia"}],
[{firstName: "Josh", lastName: "Pattison",country: "USA"}]
}
Code
{Data.attributes.map((details) => (
<TableBody data={[
{firstName: details.attributes.filter(
(x) => x.displayName === "first name"
)[0].value,
lastName: details.attributes.filter(
(x) => x.displayName === "last name"
)[0].value,
country: details.attributes.filter(
(x) => x.displayName === "country"
)[0].value},
]}>
</TableBody>
...

you can use Object.entries() to get a 2D array of your object and use something like forEach or map to have loop over it and create the desired data shape:
const finalResult = {}
Object.entries(apiData).map(([key, value]) => {
// do what ever you want here and fill your desired structure
})

Related

Typescript / Angular | Removing First Object of an Array

my Button in .html
<button (click)="deleteFirst()">Delete First</button>
My array and function in .ts:
persons = [
{surname: "Tom", lastname: "Brown"},
{surname: "Ben", lastname: "Smith"},
{surname: "Alan", lastname: "Black"},
{surname: "Nick", lastname: "White"}]
// this does not work
deleteFirst = () => {
this.persons[0].shift;
}
How can I remove the first / last Object of an array?
shift method does not work that way. You need to call it, preferably on an Array.
Your version should be like this, if you are ok with mutating source Array:
deleteFirst = () => {
this.persons.shift();
}

How to filter an object for display based on key names in React?

I have a state object that includes multiple address lines
{
name: "fred",
homeStreet1: "1 main st"
homeStreet2: "Apt A"
}
How can I iterate over the address lines to display them in React?
I tried:
{state.filter(entry => { entry.key.match(/homeStreet/) &&
<tr key={entry.value}>
<td><label htmlFor={entry.key}/>
<input
type="text"
id={`homeStreet${entry.value + 1}`}
value={entry.value}
size="20"
onChange={(e) => updateState(e.target.id, e.target.value )} />
</td>
</tr >;
})}
but I get
Expected an assignment or function call and instead saw an expression no-unused-expressions
Object.entries (doc) would fulfill your way of thinking with object's key-value pairs
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs
const obj = {
name: 'fred',
homeStreet1: '1 main st',
homeStreet2: 'Apt A'
}
Object.entries(obj).map(([key, value]) => {
if (key.match(/homeStreet/)) {
console.log(key, value)
// Do what you want then..
}
})
Supposing that all the addresses lines are home<something> you could do something like:
let state = {
name: "fred",
homeStreet1: "1 main st",
homeStreet2: "Apt A"
}
let filtered_keys = (obj, filter) => {
let key, keys = []
for (key in obj)
if (obj.hasOwnProperty(key) && filter.test(key))
keys.push(key)
return keys
}
let filteredAddress = filtered_keys(state, /home/)
console.log(filteredAddress)
filteredAddress.forEach(el => {
console.log(state[el])
})

How to convert an array of dictionaries into an array of keys using react

Given a list:
let names = [{name: "bobby"}, {name: "sydney"}, {name: "Paul"}, {name: "Grace"}
I want the output to be ["bobby", "sydney", "Paul", "Grace"]
Here is what I have tried:
var items = Object.keys(names).map(function(i) {
return names[i];
})
const items = Object.keys(names).map((key)=>names[key]);
this.setState({items});
console.log(this.state.items);
names.map(({ name }) => name)
const names = [{
name: "bobby"
}, {
name: "sydney"
}, {
name: "Paul"
}, {
name: "Grace"
}];
const keys = names.map(({
name
}) => name);
console.log(keys);
A note about react keys, they should be unique within the rendered siblings, i.e. they should be unique within the dataset. Names alone may not provide sufficient uniqueness.
A second note, you might not want to generate your react keys separately from where you need them, i.e. generally they are created when you are mapping JSX.
This is not really related to React. You can do that with JavaScript, for instance using API like map().
Here is an example:
let arr = names.map(obj => obj.name);

Need to find the way to slice this array to show only n customers

So , i basically want to show only 5 customer per page, i'll later add a pagination bar but at the moment i want to show only 5 customer, i have tried to slice after the map function, but im kinda new to react and redux and im not sure if that's the way.
const Setting = ({
itemFromPage,
BBDDCustomer
}) => {
console.log({BBDDCustomer});
const renderRows = BBDDCustomer.data.map((customer, customerIndex) => { //how to slice this array
return (
<tr key={customerIndex}>
<td>{BBDDCustomer.data[customerIndex].name}</td>
<td>{BBDDCustomer.data[customerIndex].address}</td>
<td>{BBDDCustomer.data[customerIndex].postalCode}</td>
<td>{BBDDCustomer.data[customerIndex].city}</td>
<td>{BBDDCustomer.data[customerIndex].country}</td>
<td>{BBDDCustomer.data[customerIndex].telephone}</td>
<td>{BBDDCustomer.data[customerIndex].email}</td>
<td><input type="checkbox" id="customerIndex" value="mod"/></td>
<td><input type="checkbox" id="customerIndex" value="Del"/></td>
</tr>
);
});
return (
<div>
<Table>
</div>
);
};
This is the format file where the customer are:
const BBDDCustomer = {
ui_labels: {
name: 'Name',
address: 'address',
postalCode: 'Postal Code',
city: 'City',
country: 'Country',
telephone: 'Telephone',
email: 'Email',
modified: 'Modified',
delete: 'Delete'
},
data: [
{
name: 'n1',
address: 'a1',
postalCode: 'PC 1',
city: 'c 1',
country: 'cou 1',
telephone: 'tel 1',
email: 'em 1'
}
}
It is better to get a sub-array and render it than render the whole array and get a sub-array.
There is a standard Javascript slice(from, count?) method to get a part of array, first parameter tells the index to start with, second optional parameter is the number of elements to be included
You would use it like so:
const renderRows = BBDDCustomer.data.slice(0, 5).map((customer, customerIndex) => { ... };
It would return first 5 elements which you would map with your array function.

Destructure Multiple Object Array

I am trying to retrieve objects from an array and select them individually. When an object is returned my tables cells are fill with that object i.e([object Object]), instead of the properties of that object filling the table. I know I probably need to destructure the returned array to retrieve the individual objects. However, I cannot find a way to destructure the array and send the objects to my html page. This is my code:
app.get('/lastName/:Name', function(req, res) {
var newArr = foo.lookupByLastName(req.params.Name);
res.type('text/html');
res.render('last', {LName: newArr});
}
Console.log(newArr) returns full array:
[{id:1, firstName: 'John', lastName: 'Doe'},
{id:1, firstName: 'James', lastName: 'Smith'},
{id:1, firstName: 'Jane', lastName: 'Doe'},
{.... ...]
I am trying to get something in return like this:
{id:1, firstName: 'John', lastName: 'Doe'}
{id:2, firstName: 'James', lastName: 'Smith'}
{id:3, firstName: 'Jane', lastName: 'Doe'}
Inside my html page I am trying to iterate over the returned objects and place each object in a single row and the corresponding properties in the other cells of a table.
<table border=1>
<tr>
{{#each LName}}
<td>
{{this}}
</td>
{{/each}}
</tr>
</table>
I found a temporary solution. However, with this solution I now need to create a loop that would give me the output for the res.render(). I create a loop thinking I could place the string in res.render but was given an error. This is what I did:
app.get('/lastName/:Name', function(req, res) {
var newArr = foo.lookupByLastName(req.params.Name);
res.type('text/html');
res.render('last', {Per1: newArr[0], Per2: newArr[1], Per3:newArr[3] });
}
This is the look I would have used if it worked:
text ="{";
for (;newArr[i];)
{text+="Per"+i+":"+ "newArr["+i+"],";
i++;}
text+='}';
With this loop res.render would look like:
app.get('/lastName/:Name', function(req, res) {
var newArr = foo.lookupByLastName(req.params.Name);
res.type('text/html');
res.render('last', text);
}

Resources