Create array of arrays from object properties in ReactJS - javascript

I have to create an array of arrays based on some object attributes.
So my object looks like this:
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
}
Based on the userIds and dateIds I have to create an array of arrays with every attribute like this:
[[projectId, userId, dateId, task, duration, description]] <- this is what every number means
For every userId and dateId i have to create a new array.
And based on my example should be like this:
[[5, 2, 99, 'task', 8, 'description'],
[5, 3, 99 , 'task', 8, 'description'],
[5, 1, 99, 'task', 8, 'description'],
[5, 5, 99, 'task', 8, 'description'],
[5, 2, 100, 'task', 8, 'description'],
[5, 3, 100, 'task', 8, 'description']
... etc]]
Hope i explained my issue well. Thank you for your time!
My function:
const data = { projectId: 5, userIds: [2, 3, 1, 5], date: [99, 100, 101, 102], task: 'task', duration: 'duration', description: 'description' }
const parentArray = []
data.date.map(object =>
data.userIds.map(anotherObject => {
// console.log(anotherObject, object)
parentArray.push([data.projectId, object, anotherObject, data.task, data.duration, data.description])
}
))
console.log(parentArray)

const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
}
const result = data.userIds.map(uid => {
return data.dateIds.map(did => [data.projectId, uid, did, data.task, data.duration, data.description])
}).flat();
console.log(result);

Not exactly what you asked for but using your example you can create an array of objects which might add clarity by naming the properties (if some other user needs something like this). Note how I pass in the data and reference it with this and loop through the dateId's. Key is I never have to reference the original array, perhaps making this more maintainable internally;
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
};
let x = [];
data.userIds.forEach(function(userid, index) {
this.dateIds.map((dateid, idx) => {
x.push({
project: this.projectId,
user: userid,
dateid: dateid,
tsk: this.task,
dur: this.duration,
desc: this.description
});
});
}, data);
x.forEach(function(el, index, array) {
console.log(el);
});

Related

How to check with an array have some values

How to verify with i have only 2 or 3 numbers inside this?
without this ----> if(Array.includes(1) && !Array.includes(3))
const servicesTest: IServices[] = [
{
id: '1',
name: 'Hair',
price: 25,
icon: 'https://cdn-icons-png.flaticon.com/512/7478/7478480.png'
},
{
id: '2',
name: 'Beard',
price: 20,
icon: 'https://cdn-icons-png.flaticon.com/512/7578/7578754.png'
},
{
id: '3',
name: 'Eyebrow',
price: 15,
icon: 'https://cdn-icons-png.flaticon.com/512/2821/2821012.png'
}
]
if the client choose hair + beard this will be 40 not 45.
I´m doing this:
const name = findServices.map(services => services.name)
if (name.includes('Hair') && name.includes('Beard') && !name.includes('Eyebrown')) {
return (
setTotalDay(prevState => prevState + 40),
setTotalMonth(prevState => prevState + 40)
)
}
I would create an array of discounts like this:
const discounts = [{
price: 30,
ids: [1, 2],
}];
Then check if the array has only discounted items like this:
array.length === discount.ids.length && array.every((item) => discount.ids.includes(item.id))
const discounts = [{
price: 30,
ids: [1, 2],
}];
const discounted = [{
id: 1,
name: 'Hair',
price: 20,
},
{
id: 2,
name: 'Beard',
price: 30,
},
];
const fullPrice = [{
id: 1,
name: 'Hair',
price: 20,
},
{
id: 2,
name: 'Beard',
price: 30,
},
{
id: 3,
name: 'Tea',
price: 30,
},
];
console.log("discounted", getTotal(discounted));
console.log("full price", getTotal(fullPrice));
function getTotal(array) {
for (const discount of discounts) {
if (
array.length === discount.ids.length &&
array.every((item) => discount.ids.includes(item.id))
) {
return discount.price;
}
}
return array.reduce((sum, item) => sum + item.price, 0);
}
answering your question before the edit.
Assuming we have this array
const Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Let's say we want to check if values 2 and 3 exist.
We store the values in an array let toCheck = [2,3];
We can use function every to loop all the elements of toCheck array against the Array const
Example Follows:
const Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let toCheck = [1,2];
const allExist = toCheck.every(value => {
return Array.includes(value);
});
Hope it helps.

Using ES6, what is the cleanest way to reassign properties in an object

Say I have an object as follows:
const data = {
title: 'firstStackOverFlowQuestion!',
id: '100',
datePosted: '04-10-2022',
options: [
{
questionId: 1,
difficultyLevel: 1,
difficultyScale: 10,
complexity: 2,
complexityScale: 10,
},
{
questionId: 2,
difficultyLevel: 4,
difficultyScale: 10,
complexity: 3,
complexityScale: 10,
},
{
questionId: 3,
difficultyLevel: 8,
difficultyScale: 10,
complexity: 6,
complexityScale: 10,
},
]
}
What is the cleanest way to reduce the options array to just two properties, to show the below:
const data = {
title: 'firstStackOverFlowQuestion',
id: '100',
datePosted: '04-10-2022',
options: [
{
questionId: 1,
difficultyLevel: 1,
},
{
questionId: 2,
difficultyLevel: 4,
},
{
questionId: 3,
difficultyLevel: 8,
},
],
}
Any suggestions would be most welcome! I imagine mapping, reducing, and /or using the spread operator would offer the cleanest solutions.
As you said, map + ... (spread):
const result = {
...data,
options: data.options.map(
({questionId, difficultyLevel}) => ({questionId, difficultyLevel})
)
}
Use map() along with destructuring.
data.options = data.options.map(
({questionId, difficultyLevel}) => ({questionId, difficultyLevel})
);

How to put dynamic data under a array of objects?

This is how I get the data:
const dataSaved = [{
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "aslkasad",
subtotal: 2,
taxAmount: 4,
total: 3
}, {
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "ldfgfgdf",
subtotal: 2,
taxAmount: 4,
total: 3
}]
So basically I have made a method in which I'm filtering an array of objects and just taking out the fields I need:
getDataParsed(dataSaved, storeFieldRequired) {
const barData = [];
for (const store of dataSaved) {
barData.push({
data: [store.storeFieldRequired],
label: store.storeId
});
}
return barData;
}
When I want to get an specific field of the array, my [store.storeFieldRequired] brings undefined.
How can I solve it?
Instead of using store.storeFieldRequired, it is needed to use store[storeFieldRequired]. They have different meanings.
store.storeFieldRequired means to get the value of storeFieldRequired key on store object.
store[storeFieldRequired] means to get the value of storeFieldRequired variable value key on store object.
const dataSaved = [{
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "aslkasad",
subtotal: 2,
taxAmount: 4,
total: 3
}, {
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "ldfgfgdf",
subtotal: 2,
taxAmount: 4,
total: 3
}];
function getDataParsed(dataSaved, storeFieldRequired) {
const barData = [];
for (const store of dataSaved) {
barData.push({
data: [store[storeFieldRequired]],
label: store.storeId
});
}
return barData;
}
console.log(getDataParsed(dataSaved, 'count'));
Simply, using Array.prototype.map, you can get the result.
const dataSaved = [{
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "aslkasad",
subtotal: 2,
taxAmount: 4,
total: 3
}, {
count: 52,
deliveryAmount: 0,
discountAmount: 7,
guests: 2,
refundedAmount: 9,
serviceChargeAmount: 4,
storeId: "ldfgfgdf",
subtotal: 2,
taxAmount: 4,
total: 3
}];
function getDataParsed(dataSaved, storeFieldRequired) {
return dataSaved.map((item) => ({
data: [item[storeFieldRequired]],
label: item.storeId
}));
}
console.log(getDataParsed(dataSaved, 'count'));
Access the variable with bracket-[] notation. Example => data: [store[storeFieldRequired]].
getDataParsed(storeData, storeFieldRequired) {
const barData = [];
for (const store of storeData) {
barData.push({
data: [store[storeFieldRequired]], // change this line from data: [store.storeFieldRequired] to data: [store[storeFieldRequired]]
label: store.storeId
});
}
return barData;
}

Trying to create a new object form a data model

I have a data model like this.
data: object = {
date: '11/11/18',
data: [3, 4, 7, 2, 5, 6, 8, 8]
}
The data array is from some inputs from the user. Starting from index 0, I would like them to be career, finances, personalGrowth, health, family, relationships, socialLife, attitude.
What im trying to do is get the lowest score (which would be 2 'health') and add it to an object like so.
data: object = {
lowestScore = 2,
lowerScoreName = 'Health'
}
Im fairly new to javaScript and im stuck on how to work this out.
Thanks
You could just make two related arrays (associative arrays) that look like this:
data: object = {
dataTypes: ['Career', 'Finances', 'Personal Growth', 'Health', 'Family', 'Relationships', 'Social Life', 'Attitude'],
dataValues: [3, 4, 7, 2, 5, 6, 8, 8],
}
Then obtain the lowest score:
lowestScore: Math.min(this.dataValues),
lowestScoreIndex: this.dataValues.indexOf(this.lowestScore);
And set the name of the lowest score:
lowestScoreName: this.dataTypes[lowestScoreIndex]
And there you go! Here's the full object:
data: object = {
dataTypes: ['Career', 'Finances', 'Personal Growth', 'Health', 'Family', 'Relationships', 'Social Life', 'Attitude'],
dataValues: [3, 4, 7, 2, 5, 6, 8, 8],
lowestScore: Math.min(this.dataValues),
lowestScoreIndex: this.dataValues.indexOf(this.lowestScore);
lowestScoreName: this.dataTypes[lowestScoreIndex]
}

Iterate over multidimensional array, filter and create new one in javascript

I found this post but it's not really what I'm looking for. I have a huge JSON file with this structure:
{
foo: [1, 2, 3, ...],
bar: [
{
name: 'abc',
cl: 2,
data: [
[[2, 4, 6], [4, 5, 6]],
[[5, 3, 5], [5, 7, 9]],
[[6, 8, 9], [6, 8, 9]],
...
]
},
{
name: 'def',
cl: 1,
data: [10, 20, 30, ...]
}
]
}
I have a class representing the object and I can extract the properties and the objects inside the parent object. The foo property is mandatory while the bar property is optional. data is a numeric array that can be 1D or 3D. The foo.length and the data.length are always the same. I want to reduce the file size (in term of contents) but keeping the same structure, i.e. copy the old object to a new with exactly the same structure but shorter, so I could define a smaller length or range and get a new object, e.g. if I say to go from foo[0] to foo[1] then the data property will also go from data[0] to data[1] in the new object.
Is this possible? If yes, how can I achieve it? Maybe with map? but how?
function filter(obj, from, to){
/// ?
}
Regards.
EDIT:
The new reduced object should be something like this:
{
foo: [1, 2],
bar: [
{
name: 'abc',
cl: 2,
data: [
[[2, 4, 6], [4, 5, 6]],
[[5, 3, 5], [5, 7, 9]]
]
},
{
name: 'def',
cl: 1,
data: [10, 20]
}
]
}
You could use Array#slice for it.
function slice(obj, from, to) {
obj.foo = obj.foo.slice(from, to + 1);
obj.bar.forEach(function (a) {
a.data = a.data.slice(from, to + 1);
});
}
var object = { foo: [1, 2, 3], bar: [{ name: 'abc', cl: 2, data: [[[2, 4, 6], [4, 5, 6]], [[5, 3, 5], [5, 7, 9]], [[6, 8, 9], [6, 8, 9]], ] }, { name: 'def', cl: 1, data: [10, 20, 30] }] };
slice(object, 0, 1);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories