How do i loop through this in react - reactjs

When i use map().I got this error "this.props.getCart.items.map is not a function"
{
"70":
[
{
"numberPick": 13,
"numberPrice": 200
},
{
"numberPick": 44,
"numberPrice": 300
}
],
"81":
[
{
"numberPick": 31,
"numberPrice": 50
},
{
"numberPick": 22,
"numberPrice": 90
},
{
"numberPick": 38,
"numberPrice": 50
}
]
}
This is how i get it #redux
var newData = (state.items[action.parent] === undefined)?[]:state.items[action.parent]
state = {
...state,
items:{
...state.items,
[action.parent]:[...newData,{
numberPick:action.item,
numberPrice:action.price
}]
}
}
Results that i want.Should be like this
Your parent id is 70:
first: itemID = 13 and price = 200
second: itemID = 44 and price = 200
Your parent id is 81:
first: itemID = 31 and price = 50
second: itemID = 22 and price = 90
Can anyone please help me.Thank you so much

There is no map for Object, but you want use below
Object.keys(myObject).map(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
but easily iterate an object using for ... in:
for(var key in myObject) {
if(myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
check below code for your example.
class App extends React.Component {
constructor() {
super();
this.state = {
getCart: {
"70": [{
"numberPick": 13,
"numberPrice": 200
},
{
"numberPick": 44,
"numberPrice": 300
}
],
"81": [{
"numberPick": 31,
"numberPrice": 50
},
{
"numberPick": 22,
"numberPrice": 90
},
{
"numberPick": 38,
"numberPrice": 50
}
]
}
}
}
render() {
for (var k in this.state.getCart) {
// console.log(k);
this.state.getCart[k].map(i => {
// you want to get induvidual items
console.log('items : ', i);
console.log('numberPick : ', i['numberPick']);
console.log('numberPrice : ', i['numberPrice']);
})
}
return (
<div> check console log</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>

You can loop through object:
for (var key in this.props.getCart) {
if (this.props.getCart.hasOwnProperty(key)) {
console.log(key + " -> " + this.props.getCart[key]);
this.props.getCart[key].map(item => {/*return items*/})
}
}
Then grab the array elements and push into another array.
How do I loop through or enumerate a JavaScript object?

Related

EDIT-How can I have my specific format using Object.entries?

I have these data from my api (1) and the format I want to have is this one(2), how can I do that in my front-end using Object.entries in REACT, in such a way I can modify my (1) to have (2) please ? I tried but not working...
(1):
{
"myData": [
{
"Peter": 12,
"Donald": 15,
"Huston": 65
}
],
"myOtherData": [
{
"location": "Dublin",
"country":"Irland"
}
]
}
(2):
{
"myData": [
{
"name": "Peter",
"age": "12"
},
{
"name": "Donald",
"age": "15"
},
{
"name": "Huston",
"age": "65"
}
],
"myOtherData": [
{
"location": "Dublin",
"country":"Irland"
}
]
}
I was thinking using destructuration like this :
const d= {myData, myOtherData}
const newData = Object.entries(...)//change myData here ??
Lets be fancy, time to utilise flatMap, array deconstruction and some shortcuts
const a = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
console.log({
myData: Object.entries(a.myData[0])
.flatMap(([name, age]) => ({
name,
age
}))
})
const resp = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
convertedData = []
for (const person of Object.entries(resp.myData[0])) {
convertedData.push({
name: person[0],
age: person[1]
})
}
const data = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
console.log(
Object.entries(data.myData[0])
.reduce( (acc,[name,age])=>acc.concat({name,age}),[] )
)
lets say
var myData = {
"Peter": 12,
"Donald": 15,
"Huston": 65
}
var finalData = Object.entries(myData).map(entry => {
const[key,value] = entry;
return {
name:key,
age:value
}
})
console.log(finalData)

How to get the minimum value by react js

In the code below, I am trying to run {this.renderCost(data,'mina')} with react js. I would like to obtain the minimum value of total using the code below, but total of an object that value of nameis Equal to for example mina(or other name because it will be changed).
I tried the following :
Firstly push the value of total using indents.push(elem.total), the expected output for this part is [2000,1000] and then get minimum value of array by Math.min(...indents),the expected output for this part is [1000] but the function doesn't work.
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
],
"total":"2000"
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
],
"total":"1000"
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
],
"total":"1000"
}
}
]
renderCost(data,name){
let indents = [];
data.map((elem) => {
this.renderTotal(elem,name,indents)
})
}
renderTotal(elem,name,indents){
for(let i = 0 ; i < elem.info.length;i++){
if (elem.info[i].name == name){
indents.push(elem.total)
}
return (
Math.min(...indents)
)
}
}
The data structure you're working with isn't ideal for this particular search however you can get to your answer with the following:
const minTotalByName = (data, name) => {
const totals = data
.filter(x =>
x.obj.info.find(y => y.name === name)
).map(x => x.obj.total);
return Math.min(...totals);
}
const min = minTotalByName(data, "mina"); // 1000
To find the min value for the name you can use below code:
const { useState } = React;
function App() {
const [name, setName] = useState("");
const filtered = data
.filter(obj => obj.obj.info.some(n => n.name === name))
.map(obj => Number(obj.obj.total));
const min = filtered.length !== 0 ? Math.min(...filtered) : "";
return (
<div>
<input onChange={(e) => setName(e.target.value)} />
<div>The result is: {min}</div>
</div>
);
}
const data = [
{
obj: {
no: "1",
info: [ { name: "maya" }, { name: "mina" } ],
total: "2000"
}
},
{
obj: {
no: "2",
info: [ { name: "maya" } ],
total: "1000"
}
},
{
obj: {
no: "3",
info: [ { name: "maya" }, { name: "Mike" } ],
total: "1000"
}
}
];
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

I need to find least count by iterating child array and seperate as multiple arrays based on parent array in angular

myData = [
{
id: 'N5604-E',
areas: [
{
test_per_week: 154,
test_per_day: 22,
},
{
test_per_week: 154,
test_per_day: 52,
},
{
test_per_week: 154,
test_per_day: 32,
},
],
},
{
id: 'RSP4-E',
areas: [
{
test_per_week: 154,
test_per_day: 12,
},
{
test_per_week: 154,
test_per_day: 29,
},
],
},
];
I need to get minimum test_per_week in each area and need to store values in an array based on IDs
I have tried iterating using for loop and for each loop:
for (let i = 0; i < this.data.length; i++) {
this.chartProducts.push(this.data[i].id);
this.capacity[i].areas.forEach((element) => {
this.myData.push(element.test_per_day);
});
}
I stuck on how to calculate the min count of test_per_day for all areas in one ID.
This can be done using Array.map() combined with Math.min() as follows:
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
Please have a look at the runnable code snippet below.
const myData = [{
"id": "N5604-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 22 },
{ "test_per_week": 154, "test_per_day": 52 },
{ "test_per_week": 154, "test_per_day": 32 }
]
},
{
"id": "RSP4-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 12 },
{ "test_per_week": 154, "test_per_day": 29 }
]
}
];
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
console.log(result);
We used a map method for iterating and return a new array and reduce for comparing the values between together and finally using the min mathematical method to get the minimum number.
const result = myData.map((item) => {
const test_per_day = item.areas.reduce(
(max, val) => Math.min(max, val.test_per_day),
item.areas[0].test_per_day
);
return { id: item.id, test_per_day };
});
Result:
[
{
"id": "N5604-E",
"test_per_day": 22
},
{
"id": "RSP4-E",
"test_per_day": 12
}
]

How to extract specific key/value during Http call in angular?

Through a HTTP call I am having a JSON file like bellow:
[
{
"totalConfirmed": 555,
"mainlandChina": 548,
"otherLocations": 7,
"deltaConfirmed": 555,
"totalRecovered": 0,
"confirmed": {
"total": 555,
"china": 548,
"outsideChina": 7
},
"deaths": {
"total": 17,
"china": 17,
"outsideChina": 0
},
"reportDate": "2020-01-22"
},
{
"totalConfirmed": 654,
"mainlandChina": 643,
"otherLocations": 11,
"deltaConfirmed": 99,
"totalRecovered": 0,
"confirmed": {
"total": 654,
"china": 643,
"outsideChina": 11
},
"deaths": {
"total": 18,
"china": 18,
"outsideChina": 0
},
"reportDate": "2020-01-23"
}
]
from that, I want to store the value of totalConfirmed, deaths & reportDate.
So my return would be something like this
{
totalConfirmed : [555,654],
death: [17, 18],
dates: ["2020-01-22", "2020-01-23"]
}
Here is the function that I have written in my service.ts:
public filteredData(): Observable<History> {
let dataHistory: History;
return this.httpClient.get(this.hostURL).pipe(
map(res => {
dataHistory.totalConfirmedPerDay.push(res["totalConfirmed"]);
dataHistory.totalDeathPerDay.push(res["deaths"]["total"]);
dataHistory.dates.push(res["reportDate"]);
return dataHistory;
})
);
}
and here is my History interface:
export interface History {
totalConfirmedPerDay: any[];
totalDeathPerDay: any[];
dates: any[any];
}
But unfortunately, it's now working. I am having this error:
ERROR TypeError: Cannot read property 'totalConfirmedPerDay' of undefined
You may do so using:
return this.httpClient.get(this.hostURL)
.pipe(
map(arr => {
return arr.map(sub => {
return {
totalConfirmed: sub.totalConfirmed,
totalDeathPerDay: sub.deaths.total,
dates: sub.reportDate
};
});
})
)
now in the subscription block:
.subscribe(res => {
let op: History = {
totalConfirmedPerDay: [],
totalDeathPerDay: [],
dates: []
};
res.forEach(e => {
op.totalConfirmedPerDay.push(e.totalConfirmedPerDay);
op.totalDeathPerDay.push(e.totalDeathPerDay);
op.dates.push(e.dates);
});
});
Typo mistake: dataHistory is not initialized.
public filteredData(): Observable<History> {
return this.httpClient.get(this.hostURL).pipe(
map(res => {
return {
totalConfirmedPerDay: res.totalConfirmed,
totalDeathPerDay: res.deaths.total,
dates: res.reportDate
};
})
);
The way to do map is
map((full:any[]) => { //I don't want full
full.map(res=>{ //I want a "resumed" of full
const obj={ //transform each element of full
totalConfirmed:res.totalConfirmed,
totalDeathPerDay:res.deaths.total,
dates.res.reportDate
}
return obj;
)
return full;
})

Issues with transforming array data

I'm trying to transform the following JSON array data structure -
From
[
{
"date": "2019-01-01",
"marks": [
{
"quantity": {
"shoes": 1,
"belt": 2,
"socks": 3
}
}
]
},
{
"date": "2019-01-02",
"marks": [
{
"quantity": {
"shoes": 4,
"belt": 5,
"socks": 6
}
}
]
}
]
To
rows: [
{
values: [ '2019-01-01', 1, 2, 3]
},
{
values: [ '2019-01-02', 4, 5, 6]
}
]
The code that I was able to try so far is this -
function myFunction() {
var response = [
{
"date": "2019-01-01",
"marks": [
{
"quantity": {
"shoes": 1,
"belt": 2,
"socks": 3
}
}
]
},
{
"date": "2019-01-02",
"marks": [
{
"quantity": {
"shoes": 4,
"belt": 5,
"socks": 6
}
}
]
}
];
var transform = response.map(function(dailyMarks) {
var row = [];
Object.keys(response).asArray().forEach(function (field) {
switch (field) {
case 'shoes':
return row.push(dailyMarks.shoes);
case 'belt':
return row.push(dailyMarks.belt);
case 'socks':
return row.push(dailyMarks.socks);
case 'date':
return row.push(dailyMarks.date);
default:
return row.push('');
}
});
return { values: row };
});
Logger.log(transform);
}
However, I'm running into this error -
TypeError: Cannot find function asArray in object 1,2. (line XX, file "Code")
Pretty sure I'm doing something wrong but have not been able to figure out where.
Objective is simply to transform the aforementioned data structure - approach doesn't really matter.
Any help would be highly appreciated! Thanks.
In ES5,
var arr1 = [
{
date: '2019-01-01',
marks: [
{
quantity: {
shoes: 1,
belt: 2,
socks: 3,
},
},
],
},
{
date: '2019-01-02',
marks: [
{
quantity: {
shoes: 4,
belt: 5,
socks: 6,
},
},
],
},
];
var out = [];
arr1.forEach(function(obj) {
obj.marks.forEach(function(mark) {
out.push({
values: [obj.date].concat(
Object.keys(mark.quantity).map(function(key) {
return mark.quantity[key];
})
),
});
});
});
console.log({ rows: out });
You could take an array of keys for the order and flatmap the marks array.
var data = [{ date: "2019-01-01", marks: [{ quantity: { shoes: 1, belt: 2, socks: 3 } }] }, { date: "2019-01-02", marks: [{ quantity: { shoes: 4, belt: 5, socks: 6 } }] }],
keys = ['shoes', 'belt', 'socks'],
rows = data.map(({ date, marks }) =>
({ values: [date, ...marks.flatMap(({ quantity }) => keys.map(k => quantity[k]))] })),
result = { rows };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let x = products.map(p=>{
return p.marks.reduce((t,m)=>{
t.push({ values: [p.date, ...Object.entries(m.quantity).map(([key, value]) => value)]})
return t;
},[])
}
).flat(2)
console.log(x)
var list=[{"date":"2019-01-01","marks":[{"quantity":{"shoes":1,"belt":2,"socks":3}}]},{"date":"2019-01-02","marks":[{"quantity":{"shoes":4,"belt":5,"socks":6}}]}];
let result = list.map(( {date, marks} ) => { return {value: [date, ...Object.values(marks[0].quantity)]};});
let wrap = {rows: result};
console.log(wrap);

Resources