Create object from two array with custom key [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 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
I have two array:
arrayA = ["Apple", "Banana", "Orange"]
arrayB = [1, 2, 3]
I need to make an object with these two array, but having custom keys.
Output desired:
{
{
id: 1,
name: "Apple"
},
{
id: 2,
name: "Banana"
},
{
id: 3,
name: "Orange"
}
}
what I have tried:
I have following some SO answer and it didnt meet my requirements:
result = {};
arrayA.forEach((item, i) => {
result["id"] = arrayB[i];
result["name"] = item;
});
the above code just reassign the value to the last item, hence I only got one object like this:
{
id: 3,
name: "Orange"
}

Just use map instead
const arrayA = ["Apple", "Banana", "Orange"];
const arrayB = [1, 2, 3];
const newArray = arrayA.map((item, i) => {
return {
"id" : arrayB[i],
"name" : item
}
});
console.log(newArray);

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]

2 arrays matchings , transformation in arrays of objects [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 1 year ago.
Improve this question
is it possible to compare 2 arrays and make object for each item with string value and boolean:
const array = ["ABC", "BCA", "CDA", "APA"];
const array2 = ["ABC", "APA"];
array2 = [{
value: "ABC",
matched: true,
},
{
value: "BCA",
matched: false,
},
{
value: "CDA",
matched: false,
},
{
value: "APA",
matched: true,
},
];
Yes:
let array = ["ABC", "BCA", "CDA", "APA"]
let array2 = ["ABC", "APA"]
const output = array.map((item) => {
let isFound = array2.includes(item);
return { value: item, matched: isFound };
})
console.log(output)

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 dynamicly access a object and then edit its content [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 1 year ago.
Improve this question
So i have for example such an object:
let htmlDom = [
{
type: "div",
att: {
class: ["test", "test2"],
id: "yoyo",
"data-hello": ["jan", "john"],
},
content: "Hello",
child: [
{
type: "div",
content: "test",
child: [{}],
},
],
},
];
And now i want to dynamicly acess it, for example: htmlDom[0].child[0].child[0], and now the numbers of children can vary and the numbers generally. lets say for example i have an array of [0, 0, 0], How can i then acess that path dynamicly by using the numbers in the array, and then change the content of the last child[0]? The thing is that for example the array can later on vary to [0,2,4,3,6] and such, and depending on the array lenght i need to create more .child[]
You can first grab the last index from your array of indexes using .pop(), and then use .reduce() on the now modified indexes array to iterate over your children arrays. By setting the accumulator as the starting htmlDom you can access the objects at each index and its child array for each iteration of .reduce(), where the child array from each object is returned. This child array is then used as the acc for the next call/iteration of your reduce method. Once you have found the last child array, you can use index which you previously popped off your array to set/update the value:
let htmlDom = [ { type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [ { type: "div", content: "test", child: [{}], }, ], }, ];
const changeByIdxs = (arr, [...idxs], value) => {
const lastIdx = idxs.pop();
const finalArr = idxs.reduce((acc, i) => acc[i].child, arr);
finalArr[lastIdx] = value;
}
changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);
The above can be implemented with for loops if you find that easier to understand:
const htmlDom = [{ type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [{ type: "div", content: "test", child: [{}], }, ], }, ];
const changeByIdxs = (arr, [...idxs], value) => {
const lastIdx = idxs.pop();
let finalArr = arr;
for (let i = 0; i < idxs.length; i++) {
const idx = idxs[i];
finalArr = finalArr[idx].child;
}
finalArr[lastIdx] = value
}
changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);

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
}

Categories

Resources