So I am trying to merge 2 arrays of objects by ID-s (ID and AUTOMOBIL) with this code I only push last array of objects(OPREMA). Someone have any idea how can I get all of them in the spot they should be?
So when ID in a1 is == 1 I need all of OPREMA in a2 witch AUTOMOBIL is equal to 1 to save it together it a1, but with this code it's only saving last one.
const a1 = [
{ ID: "2", TIP: "A3", VRSTA: "Limousine", $$hashKey: "object:3" },
{ ID: "1", TIP: "A5", VRSTA: "Coupe", $$hashKey: "object:7" },
];
const a2 = [
{
AUTOMOBIL: "1",
OPREMA: {
ID: "5",
NAZIV_OPREME: "Automatski",
VRSTA_OPREME: "2",
CIJENA: "15000",
OPIS: "Automatski mjenjač",
},
},
{
AUTOMOBIL: "1",
OPREMA: {
ID: "3",
NAZIV_OPREME: "Benzin",
VRSTA_OPREME: "1",
CIJENA: "7000",
OPIS: "Gorivo benzin",
},
},
{
AUTOMOBIL: "1",
OPREMA: {
ID: "19",
NAZIV_OPREME: "1.0",
VRSTA_OPREME: "5",
CIJENA: "7000",
OPIS: "potrosnja 3-6l",
},
},
{
AUTOMOBIL: "1",
OPREMA: {
ID: "11",
NAZIV_OPREME: "Sportback",
VRSTA_OPREME: "3",
CIJENA: "70000",
OPIS: "sportski izgled šasije",
},
},
{
AUTOMOBIL: "1",
OPREMA: {
ID: "8",
NAZIV_OPREME: "Quattro",
VRSTA_OPREME: "4",
CIJENA: "15000",
OPIS: "Pogon na sve kotače",
},
},
];
const a3 = a1.map(t1 => ({ ...t1, ...a2.find(t2 => t2.AUTOMOBIL === t1.ID) }));
//RESULT OF a3
console.log(a3);
In your question you never specified how exactly you want the elements of a2 to be saved in the a1 element. I'm assuming that you need them as a array under the OPREMA property. Your code was pretty close but instead of find you needed to use filter to keep all elements that match.
const a3 = a1.map(t1 => {
const matchingElements = a2.filter(t2 => t2.AUTOMOBIL === t1.ID);
return ({...t1, OPREMA: matchingElements.map(({ OPREMA }) => OPREMA) });
});
Related
I have these two arrays:
main:
[
{ id: "1"},
{ id: "2"},
{ id: "3"}
]
filtered:
[
{ id: "80", link_id: "1"},
{ id: "50", link_id: null},
{ id: "67", link_id: "3"}
]
I need to get the items of main which have as id those contained in filtered with the property: link_id, I tried with:
main.filter(x => filtered.includes(x.id));
the problem is that this will return null, and also this doesn't allow me to check if link_id is null
var main = [{
id: "1"
},
{
id: "2"
},
{
id: "3"
}
],
filtered = [{
id: "80",
link_id: "1"
},
{
id: "50",
link_id: null
},
{
id: "67",
link_id: "3"
}
],
result = main.filter(x =>
filtered.includes(x.id)
);
console.log(result)
Try with some() method
var main = [
{ id: "1"},
{ id: "2"},
{ id: "3"}
]
var filtered = [
{ id: "80", link_id: "1"},
{ id: "50", link_id: null},
{ id: "67", link_id: "3"}
]
console.log(main.filter(x => filtered.some(item => item.link_id === x.id) ));
you are close, basically you need to check in each item of the filtered array.
includes is more for a plain object as the documentation states.
check the snippet below, you can use findIndex, find or some to get if the element exist on the filtered array.
const main = [{
id: "1"
},
{
id: "2"
},
{
id: "3"
}
]
const filtered = [{
id: "80",
link_id: "1"
},
{
id: "50",
link_id: null
},
{
id: "67",
link_id: "3"
}
]
const resultFindIndex = main.filter(item => -1 !== filtered.findIndex(filteredItem => item.id === filteredItem.link_id))
const resultFind = main.filter(item => filtered.find(filteredItem => item.id === filteredItem.link_id))
const resultSome = main.filter(item => filtered.some(filteredItem => item.id === filteredItem.link_id))
console.log(resultFindIndex)
console.log(resultFind)
console.log(resultSome)
Given the following data set:
const users = {
"1": { id: "1", name: "Alex" },
"2": { id: "2", name: "John" },
"3": { id: "3", name: "Paul" }
};
const memberships = [
{ userId: "1", groupId: "1" },
{ userId: "2", groupId: "2" },
{ userId: "3", groupId: "1" }
];
What is an effective way to achieve following desired result?
const usersByGroupId = {
"1": [{ id: "1", name: "Alex" }, { id: "3", name: "Paul" }],
"2": [{ id: "2", name: "John" }]
}
I came up with the following (using Lodash):
const usersByGroupId = mapValues(
groupBy(memberships, "groupId"),
memberships => memberships.map(membership => users[membership.userId])
);
I'm not that familiar with big O notation, but I can imagine the performance of the above solution is pretty terrible on large sets. Any suggestions for improvement?
You don't really need lodash — you can do this in one step with reduce(). Just check if the key exists, if so push, if not set a new array and push. It just requires one iteration of the membership array and for each a lookup in the users object (which is more-or-less constant time) making this a linear time operation.
const users = {"1": { id: "1", name: "Alex" },"2": { id: "2", name: "John" },"3": { id: "3", name: "Paul" }};
const memberships = [{ userId: "1", groupId: "1" },{ userId: "2", groupId: "2" },{ userId: "3", groupId: "1" }];
let groups = memberships.reduce((obj, {userId, groupId}) => {
(obj[groupId] || (obj[groupId] = []) ).push(users[userId])
return obj
}, {})
console.log(groups)
I have below an array
{
"sec": "11",
"details": [
{
"id": "1",
"user": "Me1"
},
{
"id": "2",
"uesr": "Me2"
},
{
"id": "3",
"user": "Me3"
}
{
"id": "4",
"user": "Me4",
parentID:"2"
},
{
"id": "5",
"uesr": "Me5"
},
{
"id": "6",
"user": "Me6",
parentID:"2"
}
{
"id": "7",
"user": "Me7"
},
{
"id": "8",
"uesr": "Me8",
parentID:"7"
},
{
"id": "9",
"user": "Me9",
parentID:"7"
}
],
"isDisplay": "true"
}
and output should be like below
{
"sec":"11",
"details":[
{
"id":"1",
"user":"Me1"
},
{
"id":"2",
"uesr":"Me2",
"childs":[
{
"id":"4",
"user":"Me4",
"parentID":"2"
},
{
"id":"6",
"user":"Me6",
"parentID":"2"
}
]
},
{
"id":"3",
"user":"Me3"
},
{
"id":"5",
"uesr":"Me5"
},
{
"id":"7",
"user":"Me7",
"childs":[
{
"id":"8",
"uesr":"Me8",
"parentID":"7"
},
{
"id":"9",
"user":"Me9",
"parentID":"7"
}
]
}
],
"isDisplay":"true"
}
I can do this by simple looping,
In lodash or anything angular does this functionality.
I am clueless to start,
I just give below code
this.list = _.groupBy(this.list,"parentID");
But the output not as expected.
Please help or guide
Thanks
You need a different approach, not grouping, but creating a tree out of the related data.
This solution uses an array with id as key and with parentID as well. The code works with a single loop, because of storing of the relation of children and parent and parent to their children.
How it works:
Basically for every object in the array it takes as well the id for building a new object as the parentID for a new object.
So for example this object
{ id: "6", parentID: "2", user: "Me6" }
it generates in o first with id this property
6: {
id: "6",
parentID: "2",
user: "Me6"
}
and then this property with parentID
2: {
children: [
{
id: "6",
parentID: "2",
user: "Me6"
}
]
},
and while all object treated like this, we finally get a tree.
At the end, the children array of the root property is returned.
function getTree(data, root) {
var o = {};
data.forEach(function (a) {
if (o[a.id] && o[a.id].children) {
a.children = o[a.id].children;
}
o[a.id] = a;
o[a.parentID] = o[a.parentID] || {};
o[a.parentID].children = o[a.parentID].children || [];
o[a.parentID].children.push(a);
});
return o[root].children;
}
var data = { sec: "11", details: [{ id: "1", user: "Me1" }, { id: "2", uesr: "Me2" }, { id: "3", user: "Me3" }, { id: "4", user: "Me4", parentID: "2" }, { id: "5", uesr: "Me5" }, { id: "6", user: "Me6", parentID: "2" }, { id: "7", user: "Me7" }, { id: "8", user: "Me8", parentID: "7" }, { id: "9", user: "Me9", parentID: "7" }], isDisplay: "true" },
result = { sec: "11", details: getTree(data.details, undefined), isDisplay: "true" };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an array of objects. i want to filter array based the object has the condition.
my array is as follow :
var data = [
{
"name": "nitin",
"r_id": "1",
"t_id": "4"
},
{
"name": "test",
"r_id": "2",
"t_id": "3"
},
{
"name": "test1",
"r_id": "2",
"t_id": "4"
},
{
"name": "test3",
"r_id": "3",
"t_id": "3"
},
{
"name": "test2",
"r_id": "1",
"t_id": "1"
}]
and my object is as follows :
var obj = {
role:['1','2'],
type:['1','3']
}
where r_id is the role id and t_id is the type id
so i want the results whose role id is in 1 or 2 AND type id is in 1 or 3.
so mathematically role_id && type_id ((1||2)&&(1||3))
my output should like:
var result = [
{
'name':'test',
'r_id':2,
't_id':3,
},
{
'name':'test2',
'r_id':1,
't_id':1,
}];
var data = [
{
"name": "nitin",
"r_id": "1",
"t_id": "4"
},
{
"name": "test",
"r_id": "2",
"t_id": "3"
},
{
"name": "test1",
"r_id": "2",
"t_id": "4"
},
{
"name": "test3",
"r_id": "3",
"t_id": "3"
},
{
"name": "test2",
"r_id": "1",
"t_id": "1"
}]
var obj = {
role:['1','2'],
type:['1','3']
}
let result = data.filter(item=>{
return obj.role.indexOf(item.r_id) > -1 && obj.type.indexOf(item.t_id) > -1
})
console.log(result)
var data = [
{
"name": "nitin",
"r_id": "1",
"t_id": "4"
},
{
"name": "test",
"r_id": "2",
"t_id": "3"
},
{
"name": "test1",
"r_id": "2",
"t_id": "4"
},
{
"name": "test3",
"r_id": "3",
"t_id": "3"
},
{
"name": "test2",
"r_id": "1",
"t_id": "1"
}]
var obj = {
role:['1','2'],
type:['1','3']
}
var filterItems = data.filter(function(o){
return obj.role.indexOf(o.r_id) != -1 && obj.type.indexOf(o.t_id) != -1; });
console.log(filterItems);
You could change obj a bit, for corresponding property names in the data, you have, then use Array#filter and check with Array#every for wanted item.
var data = [{ name: "nitin", r_id: "1", t_id: "4" }, { name: "test", r_id: "2", t_id: "3" }, { name: "test1", r_id: "2", t_id: "4" }, { name: "test3", r_id: "3", t_id: "3" }, { name: "test2", r_id: "1", t_id: "1" }],
obj = { r_id: ['1', '2'], t_id: ['1', '3'] },
keys = Object.keys(obj),
result = data.filter(function (o) {
return keys.every(function (k) {
return obj[k].indexOf(o[k]) !== -1;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You just need to iterate your data and see if the keys (r_id and t_id) are present in the obj (in the respective arrays). For this you can use Array.filter
var data = [{"name":"nitin","r_id":"1","t_id":"4"},{"name":"test","r_id":"2","t_id":"3"},{"name":"test1","r_id":"2","t_id":"4"},{"name":"test3","r_id":"3","t_id":"3"},{"name":"test2","r_id":"1","t_id":"1"}]
var obj = {
role:['1','2'],
type:['1','3']
}
var result = data.filter(function(element){
return obj.role.indexOf(element.r_id) !== -1 && // element has valid role
obj.type.indexOf(element.t_id) !== -1 // element has valid type
})
console.log(result)
I have a survey system using Angular and Firebase which stores the results of users answers inside of an object specific to each user. This works well for storing data, but I've realized that it may be difficult to pull the data back out due to each object having a unique name.
I'd like to loop over each object and pull the all of the values together. So for all 50 entries find the total of comprehension.icons.damage[1]
How can I construct a loop that goes over objects with unique names like the objects below?
Here is my json structure
"usersanonymous:-JgTyGt6An3WWyLvnnuu" : {
"comprehension" : {
"-JgTzC0r_H58n7y8Al_-" : {
"date" : 1422154060632,
"icons" : [ {
"damage" : [ null, "0", "3", "3" ],
"ocular" : [ null, "2", "3", "1" ],
"physical therapy" : [ null, "0", "4", "4" ],
"skin" : [ null, "4", "0", "1" ]
} ]
}
}
},
"usersanonymous:-JgU-ryIpI-HR7D4VDkp" : {
"comprehension" : {
"-JgU0MwBwisNbjvRFGOT" : {
"date" : 1422154629142,
"icons" : [ {
"damage" : [ null, "0", "3", "4" ],
"ocular" : [ null, "1", "4", "3" ],
"physical therapy" : [ null, "2", "4", "3" ],
"skin" : [ null, "4", "1", "3" ]
} ]
}
}
}
Given your input data, I would create a function to extract just the data you're interested in. I've written this in raw javascript - if you're using jQuery you may have fun using $.map rather than for (x in y).
var data = {
"usersanonymous:-JgTyGt6An3WWyLvnnuu": {
"comprehension": {
"-JgTzC0r_H58n7y8Al_-": {
"date": 1422154060632,
"icons": [{
"damage": [null, "0", "3", "3"],
"ocular": [null, "2", "3", "1"],
"physical therapy": [null, "0", "4", "4"],
"skin": [null, "4", "0", "1"]
}]
}
}
},
"usersanonymous:-JgU-ryIpI-HR7D4VDkp": {
"comprehension": {
"-JgU0MwBwisNbjvRFGOT": {
"date": 1422154629142,
"icons": [{
"damage": [null, "0", "3", "4"],
"ocular": [null, "1", "4", "3"],
"physical therapy": [null, "2", "4", "3"],
"skin": [null, "4", "1", "3"]
}]
}
}
}
};
function extractComprehension(rawData) {
var result = [];
for (var usersanonymous in rawData) {
usersanonymous = rawData[usersanonymous];
if (usersanonymous.comprehension) {
for (var token in usersanonymous.comprehension) {
token = usersanonymous.comprehension[token];
if (token.icons) {
result.push(token.icons[0]);
}
}
}
}
return result;
}
function sumOf(objectList, property, index) {
var result = 0;
for (var o in objectList) {
var numbers = (objectList[o][property] || []);
if (numbers.length >= index) {
result += parseInt(numbers[index], 10);
}
}
return result;
}
Using this mini api you can get the sum of the properties you're interested in:
// Get the data array.
var comprehension = extractComprehension(data);
// Sum some property.
console.log(sumOf(comprehension, 'damage', 3));