This question already has answers here:
group object as 2d array by key
(3 answers)
Closed 3 years ago.
I have a list of objects
storage = [{
"name": "PAYR AS",
"year": "2016",
"importance": 0.015
}, {
"name": "ENTRILLO AS",
"year": "2017",
"importance": 0.43200000000000005
}, {
"name": "ENTRILLO AS",
"year": "2017",
"importance": 0.43200000000000005
}]
and by this array I wish to create a new array with two lists inside a list, where we have sorted by the name key, as such
list = [
[{
"name": "PAYR AS",
"year": "2016",
"importance": 0.015
}],
[{
"name": "ENTRILLO AS",
"year": "2017",
"importance": 0.43200000000000005
}, {
"name": "ENTRILLO AS",
"year": "2017",
"importance": 0.43200000000000005
}]
]
Is there any easy way to do this in javascript?
I've tried creating a set amount of new arrays and appending into them, however, then I've run into the problem that I need to know how many name-elements I have beforehand, which I do not necessarily know.
Thanks, and sorry if this is a stupid question!
Start by making a map that maps the grouping key to the items (this would in my opinion also be easier working with). In your example it's name. You can use thise map to created a nested array:
const rawData = [
{
"name":"PAYR AS",
"year":"2016",
"importance":0.015,
},
{
"name":"ENTRILLO AS",
"year":"2017",
"importance":0.43200000000000005,
},
{
"name":"ENTRILLO AS",
"year":"2017",
"importance":0.43200000000000005,
},
];
const companyToData = rawData.reduce((acc, item) => {
const foo = acc[item.name] ? acc[item.name] : [];
return {
...acc,
[item.name]: [
...foo,
item,
],
};
}, {});
const data = Object.values(companyToData);
console.log(data);
Related
This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 1 year ago.
I am trying to filter selected property from object using JavaScript.
This is my array
const odata=[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
},
{
"id": "0002",
"type": "ansd",
"name": "EARK",
"ppu": 0.67,
}
];
I want output like this - I want to select only 2 (id,type) props from the object
[
{"id": "0001","type": "donut"}
{"id": "0002","type": "ansd"}
]
We can use Array.map and some Destructuring to get the desired result.
The destructuring assignment syntax allows us to get selected values from Objects and Arrays in a convenient way.
const odata= [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, }, { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67, } ];
const result = odata.map(({ id, type}) => ({ id, type }));
console.log("Result:", result)
User Array.prototype.map() for generating a new array from an existing one.
Reference
const odata = [
{ "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
{ "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
];
const output = odata.map(node => ({
id: node.id,
type: node.type,
}))
console.log(output)
am asking after many trials of achieving what am about to ask
i have two arrays
the first one is array of offers with is_checked status true or false
like this
[
{
id:24,
name:"Discount 50",
discount_amount:"50.00",
discount_type:"price",
start_date:"2021-05-06",
end_date:"2021-05-07",
is_checked:true,
enabled:1
},
{
id:22,
name:"Discount 40",
discount_amount:"40.00",
discount_type:"price",
start_date:"2021-05-07",
end_date:"2021-05-10",
is_checked:false,
enabled:1
}
]
then i have a another array of objects that represent days according to specific period start_date and end_date
like the following
[
{
id:1,
offer_id:24,
date:"2021-05-06",
date_name:"Thursday",
discount_type:"price",
discount_amount:"50.00"
},
{
id:2,
offer_id:22,
date:"2021-05-07",
date_name:"Friday",
discount_type:"price",
discount_amount:"50.00"
},
{
id:3,
offer_id:22,
date:"2021-05-08",
date_name:"Saturday",
discount_type:"price",
discount_amount:"50.00"
}
]
What i need to achieve in simple words from the first array as you can see the offer with id 24 the is_checked status of it is set to true then in the second array which has an offer_id matches the checked id i need to attach another key called also is_checked so the result became like this
[
{
id:1,
offer_id:24,
date:"2021-05-06",
date_name:"Thursday",
discount_type:"price",
discount_amount:"50.00",
is_checked:true,
},
{
id:2,
offer_id:22,
date:"2021-05-07",
date_name:"Friday",
discount_type:"price",
discount_amount:"50.00",
is_checked:false,
},
{
id:3,
offer_id:22,
date:"2021-05-08",
date_name:"Saturday",
discount_type:"price",
discount_amount:"50.00",
is_checked:false,
}
]
and sorry if the description was too long
One way to achieve this is to make a list of all the id values in offers that have is_checked == true, then iterate over the days array, setting the is_checked property according to whether the offer_id value is in that list:
const offers = [{
"id": 24,
"name": "Discount 50",
"discount_amount": "50.00",
"discount_type": "price",
"start_date": "2021-05-06",
"end_date": "2021-05-07",
"is_checked": true,
"enabled": 1
},
{
"id": 22,
"name": "Discount 40",
"discount_amount": "40.00",
"discount_type": "price",
"start_date": "2021-05-07",
"end_date": "2021-05-10",
"is_checked": false,
"enabled": 1
}
];
const days = [{
"id": 1,
"offer_id": 24,
"date": "2021-05-06",
"date_name": "Thursday",
"discount_type": "price",
"discount_amount": "50.00"
},
{
"id": 2,
"offer_id": 22,
"date": "2021-05-07",
"date_name": "Friday",
"discount_type": "price",
"discount_amount": "50.00"
},
{
"id": 3,
"offer_id": 22,
"date": "2021-05-08",
"date_name": "Saturday",
"discount_type": "price",
"discount_amount": "50.00"
}
];
const checked = offers
.filter(({ is_checked }) => is_checked)
.map(({ id }) => id);
days.forEach(d => d.is_checked = checked.includes(d.offer_id));
console.log(days)
Using Array#forEach and Map.
Using Map map the id to is_checked.
Then for every object in days get the value of is_checked from the Map.
const
offers=[{id:24,name:"Discount 50",discount_amount:"50.00",discount_type:"price",start_date:"2021-05-06",end_date:"2021-05-07",is_checked:!0,enabled:1},{id:22,name:"Discount 40",discount_amount:"40.00",discount_type:"price",start_date:"2021-05-07",end_date:"2021-05-10",is_checked:!1,enabled:1}],
days=[{id:1,offer_id:24,date:"2021-05-06",date_name:"Thursday",discount_type:"price",discount_amount:"50.00"},{id:2,offer_id:22,date:"2021-05-07",date_name:"Friday",discount_type:"price",discount_amount:"50.00"},{id:3,offer_id:22,date:"2021-05-08",date_name:"Saturday",discount_type:"price",discount_amount:"50.00"}],
map = new Map(offers.map(o => [o.id, o.is_checked]));
days.forEach(o => (o.is_checked = map.get(o.offer_id)));
console.log(days);
This question already has answers here:
Group array items using object
(19 answers)
Closed 3 years ago.
I have an objects with similar ids
[{
"_id": "603",
"name": 'innova',
"type": 'suv',
"brand": 'toyota'
},
{
"_id": "902",
"name": 'i20',
"type": 'hashback',
"brand": 'hyundai'
},
{
"_id": "603",
"name": 'indigo',
"type": 'haskback',
"brand": 'toyota'
}]
should be converted to
[{
"_id": "603",
"name": ['innova', 'indigo'],
"type": ['suv', 'haskback'],
"brand": ['toyota', 'toyota']
}, {
"_id": "902",
"name": ['i20'],
"type": ['hashback'],
"brand": ['hyundai']
}]
i have tried using Object.keys and Object.Values by pushing them if id already exits but failed.
Use the reduce function to build an object _id based.
Then after use Object.values() to retrieve an object as you want
const data = [{
"_id": "603",
"name": 'innova',
"type": 'suv',
"brand": 'toyota'
},
{
"_id": "902",
"name": 'i20',
"type": 'hashback',
"brand": 'hyundai'
},
{
"_id": "603",
"name": 'indigo',
"type": 'haskback',
"brand": 'toyota'
}
]
const newData = data.reduce((acc, row) => {
if (!acc.hasOwnProperty(row._id)) {
// there is no rows with the _id, we push a row into our accumulator
acc[row._id] = {
"_id": row._id,
name: [row.name],
type: [row.type],
brand: [row.brand]
};
} else {
// as the row with the _id exists, we just push values in the arrays
acc[row._id].name.push(row.name);
acc[row._id].type.push(row.type);
acc[row._id].brand.push(row.brand);
}
return acc;
}, {});
console.log(Object.values(newData));
This question already has answers here:
Object array clone with subset of properties
(3 answers)
Closed 4 years ago.
I have an array of objects:
const ObjArray= [{
"id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
"name": "john",
"description": "worker",
"place": "f.1.1",
...
},
{
"id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
"name": "joe",
"description": "dev",
"stepType": "d.2.1",
...
}
];
I want to filter the array of objects above to return only specific properties from the objects.
Let's say I want to return only the id and the name of every object in a new array that would look like this:
[{
"id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
"name": "john"},
{
"id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
"name": "joe" }
I searched about that but I couldn't find out how to get it the way I want.
IMHO, you are looking for something like this using Array#map:
ObjArray= [{
"id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
"name": "john",
"description": "worker",
"place": "f.1.1" },
{
"id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
"name": "joe",
"description": "dev",
"stepType": "d.2.1",}
];
console.log(ObjArray.map(o => ({'id': o['id'], 'name': o['name']})));
If you prefer object destructuring:
ObjArray= [{
"id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
"name": "john",
"description": "worker",
"place": "f.1.1" },
{
"id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
"name": "joe",
"description": "dev",
"stepType": "d.2.1",}
];
console.log(ObjArray.map(({id, name}) => ({id, name})));
I have the following data being returned from a server (the structure of this data is something that I do not have control over)...
var data = {
"TrackingResults": [
{
"Name": "Pack One",
"Products": {
"Product": [
{
"ProductName": "Soccer Ball"
},
{
"ProductName": "Tennis Racket"
},
{
"ProductName": "Gold Putter"
}
]
},
"status": "Despatched",
"Location": "Alabama",
"Type": "Parcel"
},
{
"Name": "Pack Two",
"Products": {
"Product": [
{
"ProductName": "Backet Ball Hoop"
},
{
"ProductName": "Base Ball Glove"
}
]
},
"status": "Despatched",
"Location": "Florida",
"Type": "Parcel"
}
]
};
I would like to be able to sort each Tracking Result by the first Product Name. I can't find any code that will sort by a sub array property/value.
You should use the Array.sort method with a custom comparator function:
var resultsComparator = function (res1, res2) {
var prod1 = res1.Products.Product[0].ProductName;
var prod2 = res2.Products.Product[0].ProductName;
return prod1.localeCompare(prod2);
}
This way the ordering is based on the current locale of the web browser. You just pass the function to the sort method:
data.TrackingResults.sort(resultsComparator);
You need to write it manually like: (with the hint on localeCompare from meskobalazs's comment)
var result = data.TrackingResults.sort(function(a,b){
return a.Products.Product[0].ProductName.localeCompare(b.Products.Product[0].ProductName)
});
This should work for sorting TrackingResults