This question already has answers here:
How to convert array of model objects to object with model ids as keys?
(6 answers)
Closed 2 months ago.
I want to convert an array of objects in to object with one of the properties as a key
how to convert the array
const data = [
{
id: "first",
name: "Product 1",
type: "selection"
},
{
id: "second",
name: "Product 2",
type: "text"
},
{
id: "third",
name: "Product 3",
type: "csv"
}
]
like this
{
first: { name: 'Product 1', type: 'selection' },
second: { name: 'Product 2', type: 'text' },
third: {name: 'Product 3', type: 'csv' },
}
using ARRAY.REDUCE METHOD?
try
const data = [
{
id: "first",
name: "Product 1",
type: "selection"
},
{
id: "second",
name: "Product 2",
type: "text"
},
{
id: "third",
name: "Product 3",
type: "csv"
}
]
const obj = Object.fromEntries(data.map(item => [item.id, item]));
console.log(obj);
Check this
const data = [
{
id: "first",
name: "Product 1",
type: "selection"
},
{
id: "second",
name: "Product 2",
type: "text"
},
{
id: "third",
name: "Product 3",
type: "csv"
}
]
const result = {};
data.forEach(d=>{
result[d.id] = {
name: d.name,
type:d.type
}
});
Here's how to do using Array.reduce():
const data = [
{
id: "first",
name: "Product 1",
type: "selection"
},
{
id: "second",
name: "Product 2",
type: "text"
},
{
id: "third",
name: "Product 3",
type: "csv"
}
];
const result = data.reduce((acc, obj) => {
const { id, ...rest } = obj;
acc[id] = rest;
return acc;
}, {});
console.log(result);
Related
I want to create an array of objects inside I want to create one more array of objecrs from an array of objects.
I want array of object to be like this
[
{
id: "1",
tasks: [
{
id: "12ef-3902",
title: "Title 1",
start: "2022-06-01"
end: "2022-09-02"
},
],
},
{
id: "2",
tasks: [
{
id: "12ef-3904",
title: "Title 2",
start: "2022-02-01",
end: "2022-04-02"
},
],
},
{
id: "3",
tasks: [
{
id: "12ef-3906",
title: "Title 3",
start: "2022-10-09",
end: "2022-12-02"
},
],
}
];
And this is my current array of objects
[
{
id:"1",
productId:"12ef-3902",
productName:"title 1",
startDate:"2022-06-01",
endDate:"2022-09-02"
},
{
id:"2",
productId:"12ef-3904",
productName:"title 2",
startDate:"2022-02-01",
endDate:"2022-04-02"
},
{
id:"3",
productId:"12ef-3906",
productName:"title 3",
startDate:"2022-10-09",
endDate:"2022-12-02"
}
]
Here is my code I am not sure how to get array of object inside tasks.
var arr2 = listData.map((v) => ({
id: v.id,
}));
You can use map to process your array, using object destructuring to simplify the code:
listData = [{
id: "1",
productId: "12ef-3902",
productName: "title 1",
startDate: "2022-06-01",
endDate: "2022-09-02"
},
{
id: "2",
productId: "12ef-3904",
productName: "title 2",
startDate: "2022-02-01",
endDate: "2022-04-02"
},
{
id: "3",
productId: "12ef-3906",
productName: "title 3",
startDate: "2022-10-09",
endDate: "2022-12-02"
}
];
result = listData.map(({ id, productId, productName, startDate, endDate}) => ({
id,
tasks : [{ id : productId, title: productName, start: startDate, end: endDate }]
})
)
console.log(result)
I have a multidimensional javascript array of objects that I am trying to use to simply collate both the id and its key within the unit array to a brand new array
What is the best solution for returning the id with the key within its units array but reversed so the key of the new array is the unit id
[
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
]
Expected output - just return an array in the following format
e.g
ids = [ 10000282 => 0, 10000340 => 1, 10000341 => 2, 10000334 => 0 ]
so 10000282 would be the key, and 0 would be the value for the first iteration of the array
-- update --
I probably didn't explain the output so well the output should be as follows but in an array format.
ids[10000282] = 0
ids[10000340] = 1
ids[10000341] = 2
ids[10000334] = 0
So, I suppose you want to get the results back into a dictionary with key the nested id and value its index in the wrapping units. You can easily do that as follows:
x = [
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
];
result = x.flatMap(el => el.units.map((e,i) => ({[e.id]: i})));
console.log(result);
Here's a slightly different approach using reduce:
const data = [{
units: [{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [{
id: 10000334,
name: "Group 4",
}, ],
},
];
const result = data.reduce(
(total, current) =>
total.concat(current.units.map(({ id }, i) => ({ [id]: i }))),
[]
);
console.log(result);
It sounds like you want to the able to access the id properties directly which points to refactoring into an object or Map.
Using an Object created using Object.fromEntries()
const arr = [{ units: [{ id: 10000282, name: "Group 1", }, { id: 10000340, name: "Group 2", }, { id: 10000341, name: "Group 3", },], }, { units: [{ id: 10000334, name: "Group 4", },], },];
const result = Object.fromEntries(arr.flatMap(({ units }) => units.map(({ id }, i) => [id, i])));
console.log(result);
// { '10000282': 0, '10000334': 0, '10000340': 1, '10000341': 2 }
console.log('result[10000340] = ', result[10000340])
// result[10000340] = 1
Using a Map
const arr = [{ units: [{ id: 10000282, name: "Group 1", }, { id: 10000340, name: "Group 2", }, { id: 10000341, name: "Group 3", },], }, { units: [{ id: 10000334, name: "Group 4", },], },];
const result = new Map(arr.flatMap(({ units }) => units.map(({ id }, i) => [id, i])));
// Map(4) { 10000282 => 0, 10000340 => 1, 10000341 => 2, 10000334 => 0 }
console.log('result.get(10000340) = ', result.get(10000340))
// result.get(10000340) = 1
const arrays = [
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
];
const results = arrays.flatMap((items) => items.units.map(({id}, index) => `ids[${id}] = ${index}`));
console.log(...results);
Basicaly I have an object that has an array in it and I have a superior array of this object.
The object is the following.
category: {
name,
items: [{
id,
name,
price,
image,
}],
}
This array can look like:
[{
name: "Category 1",
items: [{
id: 1,
name: "Item 1 of category 1",
price: 12.34,
image: "/path/to/image",
},
{
id: 2,
name: "Item 2 of category 1",
price: 56.78,
image: "/path/to/image2",
}]
},
{
name: "Category 2",
items: [{
id: 3,
name: "Item 1 of category 2",
price: 87.65,
image: "/path/to/image3",
},
{
id: 4,
name: "Item 2 of category 1",
price: 43.21,
image: "/path/to/image4",
}]
}]
My question is, it's possible to search for the id since I have an array with all of this data.
Currently I am solving the problem with the following code:
var price = 0;
const menu = [];
state.user.menu.map((item, k) => {
item.category.items.forEach((itm) => menu.push(itm));
return null;
});
state.user.items.forEach((item) => {
price += menu.filter((itm) => itm.id === item.id)[0].price * item.quantity;
});
This basicaly copies every item in the array inside of the object and ignores the category name so I only have a big array.
For what I need now, I need to correlate each item with the category name, so, I can't do as it is now.
Basically, I have a list of Ids and I need to display them with the corresponding category that is in this array.
(Items to search)
[{
timestamp: "123456",
userid: "123456",
...
id: 1,
price: 12.34,
},
{
timestamp: "123456",
userid: "123456",
...
id: 3,
price: 87.65,
},
{
timestamp: "123456",
userid: "123456",
...
id: 4,
price: 43.21,
}]
(Expected Result)
[{
name: "Category 1",
items: [{
id: 1,
name: "Item 1 of category 1",
price: 12.34,
image: "/path/to/image",
}]
},
{
name: "Category 2",
items: [{
id: 3,
name: "Item 1 of category 2",
price: 87.65,
image: "/path/to/image3",
},
{
id: 4,
name: "Item 2 of category 1",
price: 43.21,
image: "/path/to/image4",
}]
}]
Any sugestions is welcome, thanks.
const data = [
{ name: "Category 1", items: [{ id: 1, name: "Item 1 of category 1", price: 12.34, image: "/path/to/image" }, { id: 2, name: "Item 2 of category 1", price: 56.78, image: "/path/to/image2" }] },
{ name: "Category 2", items: [{ id: 3, name: "Item 1 of category 2", price: 87.65, image: "/path/to/image3" }, { id: 4, name: "Item 2 of category 1", price: 43.21, image: "/path/to/image4" }] }
];
const getItemsById = (arr = []) => {
// get list of ids to search for
const ids = arr.map(({ id }) => id);
// iterate over list of objects
return data.reduce((list, elem) => {
// get current items with ids
const items = elem.items.filter(({ id }) => ids.includes(id));
// if any found, add element with filtered list
if(items.length > 0) list.push({ ...elem, items });
return list;
}, []);
}
console.log( getItemsById([{ id: 1 }, { id: 3 }, { id: 4 }]) );
Is this what you're looking for?
const obj = {
category: {
name: "Test",
items: [{
id: 1,
name: "Test",
price: 50,
image: "Test",
}],
}
}
console.log(obj.category.items[0].id);
This question already has an answer here:
How do I filter an array of object containing an array of object itself?
(1 answer)
Closed 2 years ago.
const data = [
{ name: "name1", option: "option1", category: [{ id: 1, value: "national" }] },
{ name: "name2", option: "option2", category: [{ id: 2, value: "international" }] },
{ name: "name3", option: "option3", category: [{ id: 3, value: "sports" }] },
{ name: "name4", option: "option4", category: [{ id: 4, value: "entertainment" }] },
];
I would like to filter of this array value of category
// // console.log(data);
const result = data.filter(e => {
return e.category.filter(b => b.value === 'national')
})
// I want output like bellow
{ name: "name1", option: "option1", category: [{ id: 1, value: "national" }] },
I modify the code for multiple arrays in category:
const data = [
{ name: "name1", option: "option1", category: [{ id: 1, value: "national" }, {id: 1, value: "mundial" }]},
{ name: "name2", option: "option2", category: [{ id: 2, value: "international" }] },
{ name: "name3", option: "option3", category: [{ id: 3, value: "sports" }] },
{ name: "name4", option: "option4", category: [{ id: 4, value: "entertainment" }] },
];
var result = data.filter(x => x.category.some(y => y.value == "mundial"));
console.log(result);
I have an array of objects like given below
readonly allItems = [
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
And I have an array of numbers like given below
let selItems = [0,2,4];
What I'm trying to do is, filter the allItems array based on selItems array
For doing that, I wrote the following code, which is obviously wrong.
for(let i=0; i< this.allItems.length; i++){
if(selItems.includes(this.allItems[i].id)){
tempMenu.push(this.allItems[i]);
}
console.log(tempMenu);
}
I'm getting the following as output
[{
id: 0,
title: "Item 0",
belongsTo: 'admin'
}]
The result I'm expecting is like this:
[
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
]
Can anyone show me the right way to do this?
Thanks!
You might use .map instead:
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItems = [0, 2, 4];
const output = selItems.map(num => allItems.find(({ id }) => id === num));
console.log(output);
To reduce computational complexity to O(N) instead of O(N^2), you can transform it into an object indexed by id first:
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItems = [0, 2, 4];
const allItemsById = allItems.reduce((a, item) => {
a[item.id] = item;
return a;
}, {});
const output = selItems.map(num => allItemsById[num]);
console.log(output);
Or with filter:
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItemsSet = new Set([0, 2, 4]);
const output = allItems.filter(({ id }) => selItemsSet.has(id));
console.log(output);