Trying to figure out the best way to filter the nested object to get every category with an id of '2' or whatever. Want it so it only return those specific nodes.
const data = [
{
node: {
categories: [
{id: 2 }
]
}
},
{
node: {
categories: [
{id: 3}
]
}
},
{
node: {
categories: [
{id: 3}
]
}
},
{
node: {
categories: [
{ id: 5 }
]
}
},
{
node: {
categories: [
{ id: 2 }
]
}
},
]
Tried something like this but doesn't seem to work.
return data.filter(e => {
return e.node.categories.forEach(category => {
category.id == '2';
});
});
If you want to return any node which has a category id of 2, you can filter based on some of the id values being equal to 2:
const data = [
{
node: { categories: [ { id: 2 } ] }
},
{
node: { categories: [ { id: 3 } ] }
},
{
node: { categories: [ { id: 3 } ] }
},
{
node: { categories: [ { id: 5 } ] }
},
{
node: { categories: [ { id: 2 } ] }
},
]
const result = data.filter(e => e.node.categories.some(c => c.id == 2));
console.log(result);
we can use find to search if the category contain specific id or not.
const data = [
{
node: {
categories: [{ id: 2 }],
},
},
{
node: {
categories: [{ id: 3 }],
},
},
{
node: {
categories: [{ id: 3 }],
},
},
{
node: {
categories: [{ id: 5 }],
},
},
{
node: {
categories: [{ id: 2 }],
},
},
];
const result = data.filter(({ node }) => {
return node.categories.find((cat) => cat.id === 2);
});
console.log(result);
Related
I have an array of objects as the following
const sample = [
{ id: '1' },
{ id: '1.1' },
{ id: '1.1.1' },
{ id: '1.1.2' },
{ id: '1.2' },
{ id: '1.2.1' },
{ id: '1.2.1.1' },
{ id: '2' },
{ id: '2.1' }
];
I'd like to create a new array to include the children under their parent based on id property as the following
[
{
id: '1',
children: [
{
id: '1.1',
children: [
{ id: '1.1.1' },
{ id: '1.1.2' }
]
},
{
id: '1.2',
children: [
{
id: '1.2.1',
children: [{ id: '1.2.1.1' }]
}
]
}
]
},
{
id: '2',
children: [ { id: '2.1' } ]
}
]
I'm not sure how to do it or from where to start
Use a map to keep track of parents and children, then get the entries that are the roots as your result:
const data = [
{ id: '1' },
{ id: '1.1' },
{ id: '1.1.1' },
{ id: '1.1.2' },
{ id: '1.3' },
{ id: '1.3.1' },
{ id: '1.3.1.1' },
{ id: '2' },
{ id: '2.1' }
];
const map = new Map();
data.forEach(({ id }) => {
// exclude last bit to get parent id
const parent = id.split(".").slice(0, -1).join(".");
// our entry - needs to be like this since
// we want a reference to the same object
const entry = { id, children: [] };
// won't run if this is a root
if (parent)
// add child to parent
map.get(parent).children.push(entry);
// add to map
map.set(id, entry);
});
const result = Array.from(map)
// get roots - keys that only have one part
.filter(([key]) => key.split(".").length === 1)
// map to entry values
.map(([, value]) => value);
console.log(result);
.as-console-wrapper { max-height: 100% !important }
I have to organise the array, Getting a response array like this
let data = [
{
date: "2022-07-01T07:26:22",
tips: [
{ id: 1 }
]
},
{
date: "2022-07-01T12:05:55",
tips: [
{ id: 1 }
]
},
{
date: "2022-07-05T13:09:16",
tips: [
{ id: 1 }
]
},
{
date: "2022-07-05T13:31:07",
tips: [
{ id: 1 }
]
},
{
date: "2022-06-29T09:21:26",
tips: [
{ id: 1 }
]
}
]
The desired output :
let data = [
{
'2022-07-01': [
{
tips: [
{ id: 1 }
]
},
{
tips: [
{ id: 1 }
]
},
]
},
{
'2022-07-05': [
{
tips: [
{ id: 1 }
]
},
{
tips: [
{ id: 1 }
]
},
]
},
{
'2022-06-29': [
{
tips: [
{ id: 1 }
]
},
]
}
]
I need to get data with the same key in the above array format. I have tried different ways to achieve this but have not gotten the proper result Which is the best way to get the desired output.
Thanks in advance!!!
Here is a solution using reduce. Grouping first using reduce and after that getting the values of the object using Object.values
let data = [ { date: "2022-07-01T07:26:22", tips: [ { id: 1 } ] }, { date: "2022-07-01T12:05:55", tips: [ { id: 1 } ] }, { date: "2022-07-05T13:09:16", tips: [ { id: 1 } ] }, { date: "2022-07-05T13:31:07", tips: [ { id: 1 } ] }, { date: "2022-06-29T09:21:26", tips: [ { id: 1 } ] }]
let res = Object.values(data.reduce((acc,{date,tips})=>{
let key = date.substring(0,10)
acc[key] = acc[key] || {[key]:[]}
acc[key][key].push({tips})
return acc
},{}))
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
HI All I am having two array of object my aim is to compare them and filter out the matched result
my data looks like this
let data1 = [
{
name:'tom',
process:'flipkart',
master:'pharma',
profiles: [
{
level:'begginer',
language:'hindi',
role:['flp_admin','flp_teacher']
}
]
},
{
name:'jeo',
process:'amazon',
master:'science',
profiles: [
{
level:'begginer',
language:'english',
role:['amz_admin']
}
]
},
{
name:'jerry',
process:'email',
master:'it',
profiles: [
{
level:'begginer',
language:'urdu',
role:['eml_teacher']
}
]
}
]
let data2 = [
{
masterName:'Pharma',
businessProcess: [
{ label:'flipkart', value:'flipkart' },
{ label:'amazon', value:'amazon' }
]
},
{
masterName:'science',
businessProcess: [
{ label:'flipkart', value:'flipkart' },
{ label:'amazon', value:'amazon' }
]
},
{
masterName:'it',
businessProcess: [
{ label:'email', value:'email' },
{ label:'amazon', value:'amazon' }
]
}
I want to compare data1 with data2 and return the match from data2 if master of data1 matches with masterName of data2 and if business of data1 matches with businessProcess.label of data2.
Could anyone please tell me how can I do it?
You can use Array.filter and Array.find to loop over and find the matching items:
let data1 = [{
name: 'tom',
process: 'flipkart',
master: 'pharma',
profiles: [{
level: 'begginer',
language: 'hindi',
role: ['flp_admin', 'flp_teacher']
}]
},
{
name: 'jeo',
process: 'amazon',
master: 'science',
profiles: [{
level: 'begginer',
language: 'english',
role: ['amz_admin']
}]
},
{
name: 'jerry',
process: 'email',
master: 'it',
profiles: [{
level: 'begginer',
language: 'urdu',
role: ['eml_teacher']
}]
}
]
let data2 = [{
masterName: 'Pharma',
businessProcess: [{
label: 'flipkart',
value: 'flipkart'
},
{
label: 'amazon',
value: 'amazon'
}
]
},
{
masterName: 'science',
businessProcess: [{
label: 'flipkart',
value: 'flipkart'
},
{
label: 'amazon',
value: 'amazon'
}
]
},
{
masterName: 'it',
businessProcess: [{
label: 'email',
value: 'email'
},
{
label: 'amazon',
value: 'amazon'
}
]
}
];
console.log(data1.filter((d) => {
return data2.find((d2) => {
//check if data matername equals data1 master
// or if data1.process value exists in one of the item of businessProcess as value
return d2.masterName == d.master || d2.businessProcess.find(b => b.value === d.process);
});
}));
Currently I have two different array of objects and my end result is I am trying to have one single array of objects.
const postIds = [
{ id: 4938960132 },
{ id: 5586491011 },
{ id: 4671908225 },
{ id: 4594788047 },
{ id: 4657970305 }
]
const images = [
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]
What I am hoping to have at the end is a data structure like the following
const newData = [
{ id: 4938960132, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
{ id: 5586491011, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
{ id: 4671908225, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' },
{ id: 4594788047, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg'},
{ id: 4657970305, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]
I've been trying a lot of different things here such as reduce, spread operator and other es6 functions but cannot seem to get the data structure that I am looking for.
Any help would be much appreciated
Assuming the two arrays have the same length:
const newData = [...postIds.map((postId, i) => Object.assign({}, postId, images[i]))];
Alternativelly, with ... operator:
const newData = [...postIds.map((item, i) => {
return {
...item,
...images[i]
};
})];
Working snippet:
const postIds = [
{ id: 4938960132 },
{ id: 5586491011 },
{ id: 4671908225 },
{ id: 4594788047 },
{ id: 4657970305 }
]
const images = [
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' },
{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]
const newData = [...postIds.map((item, i) => Object.assign({}, item, images[i]))];
console.log(newData)
You creduce both array by mapping the objects at the same index and by assigning to a new object.
This works for an arbitrary count of arrays.
const
postIds = [{ id: 4938960132 }, { id: 5586491011 }, { id: 4671908225 }, { id: 4594788047 }, { id: 4657970305 }],
images = [{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }],
result = [images, postIds].reduce(
(r, a) => a.map((o, i) => Object.assign({}, o, r[i])),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have the following object:
var entries = [
{
fields: {
tags: [
{ fields: { id: "football" } },
{ fields: { id: "running" } },
{ fields: { id: "tennis" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "tennis" } },
{ fields: { id: "football" } },
{ fields: { id: "rugby" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "cricket" } },
{ fields: { id: "running" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "football" } },
{ fields: { id: "rugby" } }
]
}
}
];
Now, I want to sort the array using another array: var testArray = ["football", "rugby"]
So any of the objects that contain both rugby and football in their fields.tags.fields.id should return first in the array, then any that just contain 1 should appear next. So the results I'm after would be:
var sortedEntries = [
{
fields: {
tags: [
{ fields: { id: "tennis" } },
{ fields: { id: "football" } },
{ fields: { id: "rugby" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "football" } },
{ fields: { id: "rugby" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "football" } },
{ fields: { id: "running" } },
{ fields: { id: "tennis" } }
]
}
},
{
fields: {
tags: [
{ fields: { id: "cricket" } },
{ fields: { id: "running" } }
]
}
}
];
I thought this might be possible using the sort() function but then I realised I need to compare my testArray to see how many items are matched. Is this possible? I can't find any examples online of what I'm trying to do and I don't know where to begin.
Solution optimized for large datasets, with temporary storage of count.
var search = ['football', 'rugby'],
entries = [{ fields: { tags: [{ fields: { id: "cricket" } }, { fields: { id: "running" } }] } }, { fields: { tags: [{ fields: { id: "football" } }, { fields: { id: "running" } }, { fields: { id: "tennis" } }] } }, { fields: { tags: [{ fields: { id: "tennis" } }, { fields: { id: "football" } }, { fields: { id: "rugby" } }] } }, { fields: { tags: [{ fields: { id: "football" } }, { fields: { id: "rugby" } }] } }],
sortedData = entries.map(function (a) {
a.count = a.fields.tags.reduce(function (r, b) { return r + !!~search.indexOf(b.fields.id); }, 0);
return a;
}, []).sort(function (a, b) { return b.count - a.count; }).map(function (a) {
delete a.count;
return a;
}, []);
document.write('<pre>' + JSON.stringify(sortedData, 0, 4) + '</pre>');
Solution optimized for small datasets, without temporary storage of count.
var search = ['football', 'rugby'],
entries = [{ fields: { tags: [{ fields: { id: "cricket" } }, { fields: { id: "running" } }] } }, { fields: { tags: [{ fields: { id: "football" } }, { fields: { id: "running" } }, { fields: { id: "tennis" } }] } }, { fields: { tags: [{ fields: { id: "tennis" } }, { fields: { id: "football" } }, { fields: { id: "rugby" } }] } }, { fields: { tags: [{ fields: { id: "football" } }, { fields: { id: "rugby" } }] } }],
sortedData = entries.sort(function (a, b) {
function f(r, c) { return r + !!~search.indexOf(c.fields.id); }
return b.fields.tags.reduce(f, 0) - a.fields.tags.reduce(f, 0);
});
document.write('<pre>' + JSON.stringify(sortedData, 0, 4) + '</pre>');
Custom sort function that filters the tags arrays and checks lengths of those matches
entries.sort(function (a, b) {
var aMatches = a.fields.tags.filter(function (item) {
return testArray.indexOf(item.fields.id) > -1
});
var bMatches = b.fields.tags.filter(function (item) {
return testArray.indexOf(item.fields.id) > -1
});
return bMatches.length - aMatches.length;
});
DEMO
It's possible with a custom sort function that would check how many items in tags exist in testArray. Something like this should work:
var testArray = ["football", "rugby"];
entries.sort(function(a, b) {
var a_score = 0;
var b_score = 0;
for (var i=0; i<a.fields.tags.length; i++) {
if (testArray.indexOf(a.fields.tags[i]) > -1) {
a_score++;
}
}
for (var i=0; i<b.fields.tags.length; i++) {
if (testArray.indexOf(b.fields.tags[i]) > -1) {
b_score++;
}
}
return b_score-a_score;
});