Tell me how to handle objects before sending axios - javascript

I'm using React.
Raise the child object to the parent.
I want to delete the unnecessary value and send it.
const before = {
address_check: true,
loan_check: true,
oneroom_disable: true,
info: {
age: 13,
name: gogo,
item: [1,2,3]
},
face: {
life: [1,2,3]
}
};
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
const after = {
address_check: true,
age: 13,
name: gogo,
item: [1,2,3]
};
How can I change the status from before to after?

You can create object from other object like below:-
const after = {
address_check: before.address_check,
age: before.info.age,
name: before.info.name,
item: before.info.item
}

You can do something like this:
// Original data
const before = {
address_check: true,
loan_check: true,
oneroom_disable: true,
info: {
age: 13,
name: gogo,
item: [1,2,3]
},
face: {
life: [1,2,3]
}
};
// Destructure required fields
const {address_check, info: {age, name, item}} = before;
// Put them together for your new object
const after = {
address_check, age, name, item
}

Related

js: How to filter object keys from an array of objects? [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 7 months ago.
I have an array similar to this one
let array = [
{
name: "1-name",
age: 18,
direction: "jsjs"
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs"
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs"
}
]
and i want to filter it based on its keys to get an array like this
[
{
name: "1-name",
direction: "jsjs"
},
{
name: "2-name",
direction: "jsjsjs"
},
{
name: "3-name",
direction: "jsjsjsjs"
}
]
Can you please help me i've try to solve it with no success
You can you the array map function.
See an example here:
const arr = [
{
name: "1-name",
age: 18,
direction: "jsjs",
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs",
phone: 7182718
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs",
phone: 7182718
}
]
const result = arr.map(({ name, direction }) => {
return {
name,
direction
};
})
console.log(result);
You Can Try This Code:
let newArr = [];
array.forEach((e) => {
newArr.push({ name: e.name, direction: e.direction });
});
The map method will work. How you implement this depends on whether you want to create a new array result with the previous objects deleted, or simply return the ones you want to keep. This will create a new array your original array will remain unaffected.
array.map(function (result) {
delete result.age;
delete result.phone;
});
console.log(result)

Reduce function wrapping data in an array

I have a reduce function that formats my data in the way i need but the only issue is the data is nested inside an array. I need to remove the outter array or just stop the reduce function from adding it in but every attempt Ive made to stop the reducer from wrapping the data in an array breaks my code. Ideally I would like my reducer to not wrap the data in an array but if thats not possible removing the array i need from inside the reducer cleanly seems like the only solution:
my data looks like this:
{
count: 4,
datapoints: [
{
Date: "2021-05-05",
score: 0,
},
{
Date: "2021-05-12",
score: 0,
},
{
Date: "2021-05-30",
score: 0,
},
{
Date: "2021-06-03",
score: 114,
},
],
};
my reducer function and api call:
const riskScores = await api.PCC.riskAssessment(userID, startdate, endDate);
const riskScoresFormatted = riskScores.datapoints.reduce((result, data) => {
const scores = result["riskAssessment"] || [];
scores.push({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
});
result["riskAssessment"] = scores;
return result;
}, []);
the output:
[riskAssessment: [{…}, {…}, {…}, {…}] ]
Ive tried just using the index of riskScoresFormatted[0] that comes back undefined. riskScoresFormatted.slice(1) just returns an empty array. Ive also tried targeting the first Item like riskScoresFormatted.riskAssessment this works but the value is sometimes null so it causes bugs later down the line.
Try changing the final reduce argument from [] to {} and I think you'll have better luck.
const riskScoresFormatted = riskScores.datapoints.reduce((result, data) => {
const scores = result["riskAssessment"] || [];
scores.push({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
});
result["riskAssessment"] = scores;
return result;
}, {});
Or, use Array.map() instead:
const riskScores = {
count: 4,
datapoints: [{
Date: "2021-05-05",
score: 0,
},
{
Date: "2021-05-12",
score: 0,
},
{
Date: "2021-05-30",
score: 0,
},
{
Date: "2021-06-03",
score: 114,
},
],
};
var riskScoresFormatted = riskScores.datapoints.map((data) => ({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
}));
console.log(riskScoresFormatted);

Where do I find the docs for lodash/fp package?

I was looking at the docs for lodash. There is a function called "filter", but it is used in a different way than the "filter" from import filter from "lodash/fp/filter";. For example, this code does not work:
import filter from "lodash/fp/filter";
var users = [
{ user: "barney", age: 36, active: true },
{ user: "fred", age: 40, active: false }
];
const newUsers = filter(users, function (o) {
return !o.active;
});
console.log(newUsers);
However, I can't seem to find the cos for "import filter from "lodash/fp/filter";
Lodash/fp function are iteratee (the callback function) first, data last, and curried, so you can create new functions, and then supply the data:
const { filter } = _; // import { filter } fron 'lodash/fp'
const filterActiveUsers = filter(o => !o.active);
const users = [
{ user: "barney", age: 36, active: true },
{ user: "fred", age: 40, active: false }
];
console.log(filterActiveUsers(users));
// which is identical to
console.log(filter(o => !o.active, users));
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>

Filter array using multiple keys

I'm trying to render grid with multiple toggling filters. I'm Using react hooks.
This is data array:
const items = [
{
name: 'hotel1',
type: 'hotel'
},
{
name: 'bar1',
type: 'bar'
},{
name: 'entertainment1',
type: 'entertainment'
},{
name: 'equipment1',
type: 'equipment'
},
{
name: 'shop1',
type: 'shop'
}
]
const initialFilters = [
{
id: 1,
active: false,
type: 'bar'
},
{
id: 2,
active: false,
type: 'shop'
},
{
id: 3,
active: false,
type: 'hotel'
},
{
id: 4,
active: false,
type: 'entertainment'
},
{
id: 5,
active: false,
type: 'equipment'
},
];
const [data, setData] = useState(items);
const [filterItems, setFilteredItems] = useState(initialFilters);
currently I'm filtering with single key that is passed
const mainFilter = (key) => {
setData(items.filter(x => x.type === key));
}
and filter buttons with grid item names are rendered:
return (
<div>
<ul>
{filterItems.map(x =>
<li key={x.type}><a
className={x.active == true ? 'active' : ''}
onClick={() => mainFilter(x.type)}>
{x.type}
</a></li>
)}
</ul>
<div>{data.map(item => <div>{item.name}</div>}</div>
</div>
)
I need to get the functionality where when pressed for example shop filter, it should only leave items with type shop. if you press bar filter, it should only leave items with bar an shop and it should work all the way to all 5 filters.
if none are selected, it should show full array.
I've tried converting logic from this:
https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72#file-filterplainarray-js
but no luck yet
You can use the function every for checking if all flags have value false
This code snippet, have an initialFilter with all the flags equal to false
const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: false,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: false,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];
let allFalse = initialFilters.every(({active}) => !active);
if (allFalse) console.log(items);
Otherwise, you can use the function filter along with the function some:
This code snippet has as active shop and entertainment
const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: true,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: true,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];
let fltered = items.filter(({type}) => initialFilters.some(({type: t, active}) => t === type && active));
console.log(fltered);
You can store the selected keys and then sort by checking if they are included:
const mainFilter = (keys) => {
setData(items.filter(x => keys.includes(x.type)));
}
This implementation would need a change in your onClick function - instead of calling a function with the key you'll need to store the keys.

Generate a new array with count of property values

I have an array in my state :
projects: [
{ title: 'todo 1', person: 'Sam', status: 'ongoing'},
{ title: 'project', person: 'Jack', status: 'complete' },
{ title: 'Design video', person: 'Tim', status: 'complete' },
{ title: 'Create a forum', person: 'Jade', status: 'overdue' },
{ title: 'application', person: 'Jade', status: 'ongoing'},],
From this array (projects), I would like to generate a new array with Javascript and to get this result :
totalByPersonAndStatus : [
{person : 'Sam', complete: 0, ongoing: 1, overdue: 0 },
{person : 'Jack', complete: 1, ongoing: 0, overdue: 0 },
{person : 'Tim', complete: 1, ongoing: 0, overdue: 0 },
{person : 'Jade', complete: 0, ongoing: 1, overdue: 1 },]
I tried it
totalProjectsByPersonAndStatus: state => {
state.projects.forEach(name => {
state. totalByPersonAndStatus["name"] = name.person;
});
return state. totalByPersonAndStatus;
The problem, if a make a console.log(this.totalByPersonAndStatus) I have an object with only the data of projects.name [name: "Jade", __ob__: Observer]
Can you help me ?
Thank you
You can use reduce
let projects =[{title:'todo1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Designvideo',person:'Tim',status:'complete'},{title:'Createaforum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'},]
let desired = projects.reduce((output,{person,status}) => {
if( output[person] ){
output[person][status]++
} else {
output[person] = {
person,
complete: Number(status==='complete'),
ongoing: Number(status==='ongoing'),
overdue: Number(status==='overdue')
}
}
return output;
},{})
console.log(Object.values(desired))
Create a new Set for people and statuses by iterating through the projects, a set has only unique values so sets are a convenience, iterate through your people set creating a new object with all the statuses initialized to 0, then iterate over the projects to increment the various statuses that apply. This method allows any number of new statuses to be added without changing the code - dynamic.
var people = new Set();
var status = new Set();
projects.forEach((p)=>{
people.add(p.person);
status.add(p.status);
});
var totalByPersonAndStatus = [];
people.forEach((person)=>{
let peeps = { "person": person };
status.forEach((stat)=>{
peeps[stat] = 0;
});
projects.forEach((project)=>{
if (project.person === person) { peeps[project.status]++; }
});
totalByPersonAndStatus.push(peeps);
});
You could use reduce and destructuring like this:
const projects=[{title:'todo 1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Design video',person:'Tim',status:'complete'},{title:'Create a forum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'}]
const merged = projects.reduce((acc,{person,status})=>{
acc[person] = acc[person] || { person, ongoing:0, complete:0, overdue:0}
acc[person][status]++;
return acc;
},{})
console.log(Object.values(merged))
The goal is create an object merged with each person as key and then increment based on the statuses:
{
"Sam": {
"person": "Sam",
"ongoing": 1,
"complete": 0,
"overdue": 0
},
"Jack": {
}
...
}
Then use Object.values, to get the final array.
You could make it a one-liner:
const projects=[{title:'todo 1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Design video',person:'Tim',status:'complete'},{title:'Create a forum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'}],
output = Object.values(projects.reduce((a,{person,status})=>
((a[person] = a[person] || {person,ongoing:0,complete:0,overdue:0})[status]++,a),{}))
console.log(output)

Categories

Resources