Get objects based on same id from an array [duplicate] - javascript

This question already has answers here:
Get list of duplicate objects in an array of objects
(8 answers)
Closed 1 year ago.
I have this long list of array and I want to filter the object return by id. For example, I want to get objects with the same id, in this case object at index 0 and index 2. How can i achieve this? I have tried the for loop method but it's not going anywhere
var arr = [
{
"name": "David",
"last_updated": "2021-04-12 15:42:51",
"id": "175",
"class": "CLASS 2019",
"stops": [
{
"total": "29",
"graduated": "1900"
},
],
},
{
"name": "Cameron",
"last_updated": "2021-04-12 15:42:51",
"id": "180",
"class": "CLASS 2021",
"stops": [
{
"total": "40",
"graduated": "2500"
},
],
},
{
"name": "Rose",
"last_updated": "2021-04-12 15:42:51",
"id": "175",
"class": "CLASS 2008",
"stops": [
{
"total": "50",
"graduated": "1000"
},
],
},
This is a short snippet that I have in mind and tried. I'm aware that it doesn't make sense hence why I'm asking here. Any explanations and workarounds is very much appreciated
for(let i=0; i<arr.length; i++) {
if(arr[i].id === arr[i].id) {
console.log(arr[i])
}
}

Please correct me if I am misunderstanding here, but you simply want to filter the array of objects to only keep objects whose id value appears more than once in the array.
If that's the case, then my solution below should answer your question. Essentially, what it does is filter the source array by a map of all id values and filters to only objects whose id appears more than once. Using length - 1 works interchangeably with length > 1 here as subtracting 1 will product a falsy value 0 for those with only one instance of their id. The only difference here would be that this would not filter objects without an id property.
If you will be dealing with objects without an id property and would like to exclude those in the final result, change length - 1 to length > 1.
const arr = [
{ name: "David", last_updated: "2021-04-12 15:42:51", id: "175", class: "CLASS 2019", stops: [ { total: "29", graduated: "1900" } ] },
{ name: "Cameron", last_updated: "2021-04-12 15:42:51", id: "180", class: "CLASS 2021", stops: [ { total: "40", graduated: "2500" } ] },
{ name: "Rose", last_updated: "2021-04-12 15:42:51", id: "175", class: "CLASS 2008", stops: [ { total: "50", graduated: "1000" } ] }
];
const uniqObjs = [];
const dupeObjs = [];
arr.forEach(obj => [uniqObjs,dupeObjs][+(arr.map(obj => obj.id).filter(id => id === obj.id).length > 1)].push(obj));
console.log('uniqObjs:',uniqObjs);
console.log('dupeObjs:',dupeObjs);

You can use array.filter
var arr = [{
"name": "David",
"last_updated": "2021-04-12 15:42:51",
"id": "175",
"class": "CLASS 2019",
"stops": [{
"total": "29",
"graduated": "1900"
}, ],
},
{
"name": "Cameron",
"last_updated": "2021-04-12 15:42:51",
"id": "180",
"class": "CLASS 2021",
"stops": [{
"total": "40",
"graduated": "2500"
}, ],
},
{
"name": "Rose",
"last_updated": "2021-04-12 15:42:51",
"id": "175",
"class": "CLASS 2008",
"stops": [{
"total": "50",
"graduated": "1000"
}, ],
},
]
const id175 = arr.filter(item => item.id === '175');
console.log(id175)

Related

Transform array of data into grouped data for SectionList component

I'll freely admit that Javascript is not my strongest language, and React Native is very new, so, there may be an obviously easy way to do this that I'm not seeing.
I've got an API that presents some transaction data in a simple structure:
[
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
I want to present this data using a SectionList component, with the transactions in sections by date. My (likely crude) attempt to solve this was going to be to transform this data into the following structure:
[
{
"date": "2021-09-10",
"transactions": [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
}
]
},
{
"date": "2021-09-09",
"transactions": [
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
}
]
},
{
"date": "2021-09-07",
"transactions": [
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
}
]
But I'm honestly lost as to how to transform this data (or if there's a better way to solve this problem). I started by using Lodash's groupBy function, which seemed promising, but it looks like SectionList doesn't want an object, it wants an array.
Transforming the output of groupBy into an array straight off drops the keys and I've got grouped data but no clear value for the section header.
Again, there's probably some deviously simple way to address this, data comes in as a flat array all the time. I appreciate any guidance, assistance, or examples anybody can point me to.
const input = [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
const result = input.reduce((accum, current)=> {
let dateGroup = accum.find(x => x.date === current.date);
if(!dateGroup) {
dateGroup = { date: current.date, transactions: [] }
accum.push(dateGroup);
}
dateGroup.transactions.push(current);
return accum;
}, []);
console.log(result)
Given an array, whenever your result is expecting to have same number of elements, use map, but since your result has different number of elements, use reduce as shown above. The idea is by having reduce, loop over each element, see if you can find the element, and push the current element into the list
The lodash groupBy just helps you with group data, you should process grouped data by converting it into your format.
const input = [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
];
const groupedArray = _.groupBy(input, "date");
let result = [];
for (const [key, value] of Object.entries(groupedArray)) {
result.push({
'date': key,
'transactions': value
})
}
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
simply
const data =
[ { id: 1, title: 'Apple Store', date: '2021-09-10', amount: '$100.00' }
, { id: 41, title: 'Zulauf, Walter and Metz', date: '2021-09-10', amount: '$14.00' }
, { id: 9, title: 'Aufderhar PLC', date: '2021-09-09', amount: '$78.00' }
, { id: 10, title: 'Bayer and Sons', date: '2021-09-07', amount: '$67.00' }
]
const res = Object.entries(data.reduce((r,{id,title,date,amount})=>
{
r[date] = r[date] ?? []
r[date].push({id,title,date,amount})
return r
},{})).map(([k,v])=>({date:k,transactions:v}))
console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0 }
With lodash you can group by the date then map to the required form:
const input = [{"id":1,"title":"Apple Store","date":"2021-09-10","amount":"$100.00"},{"id":41,"title":"Zulauf, Walter and Metz","date":"2021-09-10","amount":"$14.00"},{"id":9,"title":"Aufderhar PLC","date":"2021-09-09","amount":"$78.00"},{"id":10,"title":"Bayer and Sons","date":"2021-09-07","amount":"$67.00"}];
const result = _.map(
_.groupBy(input, 'date'),
(transactions, date) => ({ date, transactions })
)
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
you could use loadash
var result = _(data)
.groupBy(item => item.date)
.map((value, key) => ({date: key, transactions: value}))
.value();

Add is_checked key to another array of objects according to the state of the offer

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);

How to parse object1 which contains array1, array1 contains object2, object2 contains array3 and so on.. in typescript or javascript [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 am having a json response like below. I want to fetch id(s) from all levels of children so that I can put them into an array and further passed on checkbox tree.
{
"status": "SUCCESS",
"status_code": "200",
"message": "Orgnization Hierarchy",
"responseBody": {
"data": {
"id": "2",
"parentId": "0",
"value": "Company1",
"children": [
// this is level 1 object 1
{
"id": "54",
"parentId": "2",
"value": "MasterCard",
"children": [
// this is level 2 of object 1
{
"id": "56",
"parentId": "54",
"value": "Branch bangalore",
"children": [
{
"id": "51",
"parentId": "56",
"value": "Area1",
"children": [
{ id:"66",
"parentId":"56",
value: "Deposite dept.",
// this is level 3 of object 1 and so on..
"children": [...] // further expanded
}
]
},
// this is level 1 of object 2
{
"id": "5",
"parentId": "54",
"value": "Branch pune",
"children": [...]
}
]
}
]
},
// level 1 object 2
{
"id": "74",
"parentId": "2",
"value": "Axis bank",
"children": [...] // further expanded
}
]
}
}
}
So, if I want to get id [in the example above like (2, 54, 56, 51, 66,...,5,...,74 )] from every level of the children, how can we achieve that? is there any recursive way or without recursive we can achieve it?
I processed below approach :
var arrayOfids;
function parsejson(){
for(var i = 0; i < data.length; i++){
var objectid = data[i].id
var objchildren = data[i].children;
getidfromchildren(objchildren);
}
}
function getidfromchildren(arr){
for(var j=0; j < arr.length; j++){
arrayOfids.push(arr[i].id);
if(arr[i].children.length != 0){
getidfromchildren(arr);
}
}
}
You could take Array#flatMap and get all id.
This approach assumes, that all children properties have at least an empty array.
If not, you need an array as default parameter, like
getId = ({ id, children = [] }) => [id, ...children.flatMap(getId)]
// ^^^^
const
getId = ({ id, children }) => [id, ...children.flatMap(getId)],
data = { status: "SUCCESS", status_code: "200", message: "Orgnization Hierarchy", responseBody: { data: { id: "2", parentId: "0", value: "Company1", children: [{ id: "54", parentId: "2", value: "MasterCard", children: [{ id: "56", parentId: "54", value: "Branch bangalore", children: [{ id: "51", parentId: "56", value: "Area1", children: [{ id: "66", parentId: "56", value: "Deposite dept.", children: [] }] }, { id: "5", parentId: "54", value: "Branch pune", children: [] }] }] }, { id: "74", parentId: "2", value: "Axis bank", children: [] }] } } },
ids = [data.responseBody.data].flatMap(getId);
console.log(ids)

Group Javascript object based on Array Object list

I'm trying to find a way to convert this list of objects based on the group array. The tricky part I've found is iterating through the group Array and applying the object to more than one place if there are multiple groups.
I'm also trying to ignore any group that does not belong to anything. I've tried using the reduce function but I cannot get the iteration through the group array.
let cars =
[
{
"group":[],
"name": "All Makes",
"code": ""
},
{
"group":["Group A"],
"name": "BMW",
"code": "X821"
},
{
"group":["Group B"],
"name": "Audi",
"code": "B216"
},
{
"group":["Group B"],
"name": "Ford",
"code": "P385"
},
{
"group":["Group B", "Group C"],
"name": "Mercedes",
"code": "H801"
},
{
"group":["Group C"],
"name": "Honda",
"code": "C213"
}
]
To become this:
let cars = {
"Group A": [
{
name: "BMW",
code: "X821",
}
],
"Group B": [
{
name: "Audi",
code: "B216"
},
{
name: "Ford",
code: "P385"
},
{
name: "Mercedes",
code: "H801"
}
],
"Group C":[
{
name: "Mercedes",
code: "H801"
},
{
name:"Honda",
code: "C213"
}
]
};
I already tried using reduce to accomplish this but the grouping doesn't replicate if it's in more than one group.
let result = cars.reduce(function(x, {group, name}){
return Object.assign(x, {[group]:(x[group] || [] ).concat({group, name})})
}, {});
Any pointers to help with this would be much appreciated.
You can use .reduce() to loop through each car object in cars. For each group array for a given car, you can then use .forEach() to then add that group as a key to the accumulator. If the group has already been set in the accumulator, you can grab the grouped array of objects, otherwise, you can create a new array []. Once you have an array you can then add the object to the array using .concat(). Since we're using .forEach() on the group array, it won't add the object to the accumulated object if it is empty as .forEach() won't iterate over an empty array.
See example below:
const cars = [{ "group":[], "name": "All Makes", "code": "" }, { "group":["Group A"], "name": "BMW", "code": "X821" }, { "group":["Group B"], "name": "Audi", "code": "B216" }, { "group":["Group B"], "name": "Ford", "code": "P385" }, { "group":["Group B", "Group C"], "name": "Mercedes", "code": "H801" }, { "group":["Group C"], "name": "Honda", "code": "C213" } ];
const res = cars.reduce((acc, {group, ...r}) => {
group.forEach(key => {
acc[key] = (acc[key] || []).concat({...r}); // copy r so it is a different reference for each grouped array
});
return acc;
}, {});
console.log(res);
Some basic approach. #Nick's is much better.
let cars = [{
"group": [],
"name": "All Makes",
"code": ""
},
{
"group": ["Group A"],
"name": "BMW",
"code": "X821"
},
{
"group": ["Group B"],
"name": "Audi",
"code": "B216"
},
{
"group": ["Group B"],
"name": "Ford",
"code": "P385"
},
{
"group": ["Group B", "Group C"],
"name": "Mercedes",
"code": "H801"
},
{
"group": ["Group C"],
"name": "Honda",
"code": "C213"
}
]
let newCars = {};
cars.forEach(o => {
o.group.forEach(g => {
if (!newCars[g])
newCars[g] = [];
newCars[g].push({
name: o.name,
code: o.code
});
});
});
console.log(newCars);

Convert a model in given json format

I have a model in which values are stored in following format:--
Language-count=3
[0]
-ID="1"
-Name="French"
[1]
-ID="2"
-Name="English"
[2]
-ID="3"
-Name="Hindi"
Titles-count=2
[0]
-ID="1"
-Name="Video1"
[1]
-ID="2"
-Name="Video2"
Countries-count=2
[0]
-ID="1"
-Name="India"
[1]
-ID="2"
-Name="USA"
and I have to convert this model in given json format:-
var models = [
{
name: 'Language',
values: [
'English',
'French',
'Hindi'
]
},
{
name: 'Title',
values: [
'Title 1',
'Title 2'
]
},
{
name: 'Countries',
values: [
'India',
'UK'
]
}
];
In above json format I have hard coded those values of Languages,countries and Titles but I have to fetch it from the above model which I have already given.
The json Format which I am getting is following:--
{
"ID": 1,
"DealID": 1,
"Title": "Position1",
"Titles": [
{
"Icon": "hdtv",
"Name": "\nWedding Bells & Farewells\n",
"ID": 12
},
{
"Icon": "hdtv",
"Name": "Delta Farce",
"ID": 5
},
{
"Icon": "hdtv",
"Name": "Doe B: Let Me Find",
"ID": 9
}
],
"Episodes": [
{
"Icon": "episode",
"Name": "Sparkle",
"ID": 4
},
{
"Icon": "episode",
"Name": "Sparks Fly Out",
"ID": 2
},
{
"Icon": "episode",
"Name": "Uploads by Filmi Gaane",
"ID": 7
}
],
"Assets": [
{
"Icon": "file-o",
"Name": "Best of Javed Akhtar - Jukebox 2 - Javed Akhtar Top 10 Hit Songs",
"ID": 10
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party additional image 1",
"ID": 4
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party box cover",
"ID": 3
}
],
"Documents": [],
"Languages": [
{
"Icon": "globe",
"Name": "Albanian",
"ID": 70
},
{
"Icon": "globe",
"Name": "Amharic",
"ID": 96
}
],
"Territories": [],
"Countries": [
{
"Icon": "globe",
"Name": "Afghanistan",
"ID": 2
},
{
"Icon": "globe",
"Name": "Albania",
"ID": 3
},
{
"Icon": "globe",
"Name": "Algeria",
"ID": 4
}
],
"Rights": [
{
"Icon": "leaf",
"Name": "Ancillary",
"ID": 23
},
{
"Icon": "leaf",
"Name": "Finshed Episode Rights",
"ID": 20
},
{
"Icon": "leaf",
"Name": "Format Group - DO NOT USE",
"ID": 63
}
],
"Contributors": [],
"Transmissions": [],
"Available": null
}
It would be best to write a simple parser and transform your data type to JSON - which would additionally allow you to reuse the parser in the future, and convert it to other data types easily for instance.
You could look at the various YAML parsers for inspiration, which would use a similiar technique for your data set's language.
Alternatively you can create a 'hack' and just keep splitting things up if your data format is always of this format, and doesn't allow arbitrary value nesting.
List personel = new List();
var client = new RestClient("your adres");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "2893de4a-457e-46a7e8efb025");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("token", "a23a80f7-3323-4594056");
IRestResponse response = client.Execute(request);
JObject deger = JObject.Parse(response.Content);
var toplam = deger["data"]["data"].Count();
string jenp = toplam.ToString();
for (int i = 0; i < toplam; i++)
{
Personeller data = new Personeller();
data.Adi = deger["data"]["data"][i]["adi"].ToString();
data.Soyadi = deger["data"]["data"][i]["soyadi"].ToString();
data.tckimlikno = (long)deger["data"]["data"][i]["tckimlikno"];
personel.Add(data);
}

Categories