re-create an Object to be 2D Array [closed] - javascript

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 2 years ago.
Improve this question
I have an object like this
{ '2020-08': {Invoice: 21400, Receipt: 20800, ...},
'2020-09': {Invoice: 8003.6, ...},
'2020-10': {Receipt: 7779.2, ...},
'2020-11': {Invoice: 32970, ...}
}
Wanna make it to be 2d array like this
[ ['2020-08', '2020-09', '2020-10', '2020-11'],
[ 21400 , 8003.6 , 0 , 32970 ], //Invoice
[ 20800 , 0 , 7779.2 , 0 ], //Receipt
...
]

It is very easy to achieve using Object.keys.
const data = {
'2020-08': {
Invoice: 21400,
Receipt: 20800
},
'2020-09': {
Invoice: 8003.6,
Receipt: 7779
},
'2020-10': {
Receipt: 7779.2,
Invoice: 32970
},
'2020-11': {
Invoice: 32970,
}
}
const res = []
const keys = [...Object.keys(data)]
const d = Object.keys(data).map(item => {
return data[item]["Invoice"] || 0
})
const d1 = Object.keys(data).map(item => {
return data[item]["Receipt"] || 0
})
console.log([keys, d, d1])

Try:
let result = [], key= [], invoice= [], receipt = [];
Object.keys(obj).forEach((x) => {
key.push(x);
invoice.push(obj[x].Invoice || 0);
receipt.push(obj[x].Receipt || 0);
});
result = [key,invoice,receipt];

Related

How to extract numbers from an array [closed]

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 24 days ago.
Improve this question
So basically I have an array of ids and I want to return only a simple array which I want to look like this
*[1,2,3]*
instead of
*[0:[1] , 1:[2]]*
Is there any way to do it
Code
const usersWhoHavePurchasedYourCourses = usersWhoHaveTokens.filter(
(user1: any) => {
return user1.tokens
?.map((token: any) => parseInt(token.course_id))
.includes(user.courses?.map((course: any) => course.id));
});
The output looks like this
output
As I said I don`t want to return this kind of output.
Edit
In attempting to reverse-engineer your logic, wouldn't you want to filter by checking if a user has at least one course? I recommend using Array.prototype.some as your filter result.
const user = { courses: [{ id: 1 }, { id: 2 }] };
const usersWhoHaveTokens = [
{ id: 1, tokens: [{ course_id: '1' }] },
{ id: 2, tokens: [{ course_id: '2' }] },
{ id: 3, tokens: [{ course_id: '3' }] },
];
// Compute the set, for faster processing
const userCourseIds = new Set(user.courses.map((course) => course.id));
const usersWhoHavePurchasedYourCourses = usersWhoHaveTokens
.filter(({ tokens }) => tokens
.some((token) => userCourseIds.has(parseInt(token.course_id))))
.map(({ id }) => id);
console.log(usersWhoHavePurchasedYourCourses); // [1, 2]
Original response
If you object is an 'object' type, you will need to transform it into an array, and then flatten it.
const
obj = { 0: [1], 1: [2] },
arr = Object.values(obj).flat();
console.log(JSON.stringify(arr)); // [1, 2]
If you want to preserve indices:
const
obj = { 1: [2], 5: [6] },
arr = Object.entries(obj).reduce((acc, [index, value]) => {
acc[+index] = value;
return acc;
}, []).map(([value]) => value);
console.log(JSON.stringify(arr)); // [null, 2, null, null, null, 6]

Combine Objects in a js array without overwriting them [closed]

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 7 months ago.
Improve this question
i have an array like below
[
{
"202229": "8.418"
},
{
"202229": null
},
{
"202229": null
},
{
"202230": "10.713"
},
{
"202230": "0.859"
}
]
i want to convert it to below structure
[
{
"202229": "8.418",
"202229": null,
"202229": null,
"202230": "10.713",
"202230": "0.859"
}
]
Note that values are not overwritten and keys "202229" etc are dynamic . I tried using reduce methods but i couldn't get it in this format . Any help would be appreciated . Thanks
You could disperse the keys to various objects.
const
data = [{ 202229: "8.418" }, { 202229: null }, { 202229: null }, { 202230: "10.713" }, { 202230: "0.859" }, { 202231: "0.503" }, { 202231: null }],
result = data.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => {
let i = 0;
while (k in (r[i] ??= {})) i++;
r[i][k] = v;
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Dynamically assign object values to variable in JavaScript [closed]

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 1 year ago.
Improve this question
I need to assign the values of the below array of objects into defined variables which are initialized as empty strings.
What I have tried up until now:
const transaction = [{
number: 10,
value: "Ten"
},
{
number: 20,
value: "Twenty"
},
];
let transactionOneValue, transactionTwoValue, transactionOneNumber, transactionTwoNumber = "";
if (transaction.length > 0) {
transaction.forEach(item => {
[transactionOneNumber, transactionTwoNumber].forEach(num => num = item.number);
[transactionOneValue, transactionTwoValue].forEach(val => val = item.value);
});
}
Expected output:
transactionOneValue = "Ten",
transactionTwoValue = "Twenty",
transactionOneNumber = 10,
transactionTwoNumber = 20
How can I do it?
Destructuring seems to be simplest approach here, but I don't see how this would be useful. Creating separate variables for every item in a list isn't scalable.
let [
{number: transactionOneNumber, value: transactionOneValue},
{number: transactionTwoNumber, value: transactionTwoValue}
] = transaction
const transaction = [{
number: 10,
value: "Ten"
},
{
number: 20,
value: "Twenty"
},
];
let transactions = [];
if (transaction.length > 0) {
transaction.map((value, index, array) => {
for(x of Object.values(value)) {
transactions.push(x);
}
})
}
let transactionOneNumber = transactions[0],
transactionOneValue = transactions[1],
transactionTwoNumber = transactions[2],
transactionTwoValue = transactions[3];
console.log(transactionOneNumber);
console.log(transactionOneValue);
console.log(transactionTwoNumber);
console.log(transactionTwoValue);
output:
10
"Ten"
20
"Twenty"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

How to merge two array and assign each iteration a key [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have two array
arr1 = ["google.com", "none", "Twitter", "Facebook"]
arr2 = [6, 25, 1, 8]
Then my expected output would be like this
newArr = [
{
'medium': 'www.google.com',
'key': 6
},
{
'medium': 'none',
'key': 25
},
{
'medium': 'Twitter',
'key': 1
},
{
'medium': 'Facebook',
'key': 8
}
];
I have tried something like this but did not get the expected output
const result = arr1.reduce(function(result, field, index) {
result[arr2[index]] = field;
return result;
});
How can I achieve the output? Thanks.
You could do a map with index
const arr1 = ["google.com", "none", "Twitter", "Facebook"]
const arr2 = [6, 25, 1, 8]
const res = arr1.map((_, index) => ({
medium: arr1[index],
key: arr2[index],
}))
console.log(res)
This should work assuming arr1 and arr2 length always equal
function combineTwoArrays (arr1, arr2){
let result = []
for (let i = 0; i< arr1.length; i++){
result.push({
medium: arr1[i],
key: arr2[i]
})
}
return result
}

How to remove key array in javascript by keep default value [closed]

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 2 years ago.
Improve this question
Hi I want to delete key in array
here is my array
const data = [ { id: "2" } , { id: "4" } ]
I want ouput
['2','4']
here is what i try
data.map(function(item) {
//I return only item.id but output still not change
return item.id
})
That's because .map() method returns a new array, it does not alternate the current array. You need to store the returned array in another variable to get the required output like:
const data = [ { id: "2" } , { id: "4" } ]
const res = data.map(x => x.id)
console.log( res )
Or, using same variable:
let data = [ { id: "2" } , { id: "4" } ]
data = data.map(x => x.id)
console.log( data )
Map returns new array and do not alter source array. so you need to assign the result to a new variable.
const data = [{
id: "2"
}, {
id: "4"
}];
const output = data.map(function(item) {
return item.id
})
console.log(output)
Something like this? We map the key to a number and return it.
const data = [ { id: "2" } , { id: "4" } ];
var result = Object.keys(data).map(function (key) {
return Number(key);
});
console.log(result);

Categories

Resources