Related
I am trying through the array and use a Array.prototype.filter() method on every children array to find the elements whose key matches with the ones specified.
Then, I'am using Array.prototype.splice() to remove the results from the respective children array but the result is return undefined.
const inputArray = [
"Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb",
"633ac872e78fa7ebee03b8bf",
"5e69dbd7-5fee-67a9-c73f-4656f9b90715",
"d484558b-4717-b0b8-db07-68288afb4f6a",
"63922aac4ff08f52d71fa891",
"33a3182b-93a4-84b9-4c49-c955a8416197",
];
const originalArray = [{
title: "Animals",
key: "d484558b-4717-b0b8-db07-68288afb4f6a",
children: [{
title: "Color",
key: "63922aac4ff08f52d71fa891",
children: [{
title: "Black",
key: "Black-9e994ed2-823b-d1d6-4613-91d43f570fec",
},
{
title: "White",
key: "White-5d0b102a-2555-8f7c-d471-cc82a5bd9c01",
},
],
}, ],
},
{
title: "Elements",
key: "5e69dbd7-5fee-67a9-c73f-4656f9b90715",
children: [{
title: "Non metals",
key: "633ac872e78fa7ebee03b8bf",
children: [{
title: "Carbon",
key: "Carbon-e443daa4-def4-9830-796e-ee8c5a1f41d4",
},
{
title: "Nitrogen",
key: "Nitrogen-c2922569-0b2d-0e07-454d-d8411af701b7",
},
{
title: "Oxygen",
key: "Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb",
},
],
}, ],
},
{
title: "Planets",
key: "33a3182b-93a4-84b9-4c49-c955a8416197",
children: [{
title: "Composition",
key: "63b3d5cd12c06ba7ce353f76",
children: [{
title: "Chthonian planet",
key: "Chthonian planet-b3c593c1-d29e-5e14-1b11-2241e8ef2be6",
},
{
title: "Carbon planet",
key: "Carbon planet-07d67d62-afcf-fbcf-a8e8-75081cb44c2f",
},
],
}, ],
},
];
console.log(
"🚀 ~ file: TranferTree.misc.js:152 ~ onCheck ~ outputArray",
originalArray.forEach(e => {
e.children.forEach((c, i) => {
if (inputArray.includes(c.key)) {
e.children.splice(i, 1);
} else {
c.children.forEach((cc, j) => {
if (inputArray.includes(cc.key)) {
c.children.splice(j, 1);
}
});
}
});
})
);
Note: For example in the Elements => 5e69dbd7-5fee-67a9-c73f-4656f9b90715 children Non metals => 633ac872e78fa7ebee03b8bf i am only remove object with this key => Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb I want to keep the other objects that were not found this also applies to for example Composition => 63b3d5cd12c06ba7ce353f76 or Planets => 33a3182b-93a4-84b9-4c49-c955a8416197.
Since you want to preserve the original object references it will be slightly less efficient, but here's a way you can do it with recursive function calls. It provides the same output as your code, but it's correctly logging the final structure whereas yours is logging the return value of .forEach() which is undefined, by design.
const inputArray = [
"Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb",
"633ac872e78fa7ebee03b8bf",
"5e69dbd7-5fee-67a9-c73f-4656f9b90715",
"d484558b-4717-b0b8-db07-68288afb4f6a",
"63922aac4ff08f52d71fa891",
"33a3182b-93a4-84b9-4c49-c955a8416197",
];
const originalArray = [{
title: "Animals",
key: "d484558b-4717-b0b8-db07-68288afb4f6a",
children: [{
title: "Color",
key: "63922aac4ff08f52d71fa891",
children: [{
title: "Black",
key: "Black-9e994ed2-823b-d1d6-4613-91d43f570fec",
},
{
title: "White",
key: "White-5d0b102a-2555-8f7c-d471-cc82a5bd9c01",
},
],
}, ],
},
{
title: "Elements",
key: "5e69dbd7-5fee-67a9-c73f-4656f9b90715",
children: [{
title: "Non metals",
key: "633ac872e78fa7ebee03b8bf",
children: [{
title: "Carbon",
key: "Carbon-e443daa4-def4-9830-796e-ee8c5a1f41d4",
},
{
title: "Nitrogen",
key: "Nitrogen-c2922569-0b2d-0e07-454d-d8411af701b7",
},
{
title: "Oxygen",
key: "Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb",
},
],
}, ],
},
{
title: "Planets",
key: "33a3182b-93a4-84b9-4c49-c955a8416197",
children: [{
title: "Composition",
key: "63b3d5cd12c06ba7ce353f76",
children: [{
title: "Chthonian planet",
key: "Chthonian planet-b3c593c1-d29e-5e14-1b11-2241e8ef2be6",
},
{
title: "Carbon planet",
key: "Carbon planet-07d67d62-afcf-fbcf-a8e8-75081cb44c2f",
},
],
}, ],
},
];
function filterChildrenById (item, ids) {
if (item.children) {
for (let i = 0; i < item.children.length; i++) {
let child = item.children[i];
if (ids.includes(child.key)) {
item.children.splice(i, 1);
// Reduce index because we removed an item so indexing will
// be off if we don't do this
i--;
} else if (Array.isArray(child.children)) {
child = filterChildrenById(child, ids);
}
}
}
return item;
}
function filterData(data, ids) {
data.forEach(item => filterChildrenById(item, ids))
return data;
}
console.log(
"🚀 ~ file: TranferTree.misc.js:152 ~ onCheck ~ outputArray",
filterData(originalArray, inputArray)
);
You need to iterate from the end of the array, because splice changes index for the followind item.
const
keys = ["Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb", "633ac872e78fa7ebee03b8bf", "5e69dbd7-5fee-67a9-c73f-4656f9b90715", "d484558b-4717-b0b8-db07-68288afb4f6a", "63922aac4ff08f52d71fa891", "33a3182b-93a4-84b9-4c49-c955a8416197"],
data = [{ title: "Animals", key: "d484558b-4717-b0b8-db07-68288afb4f6a", children: [{ title: "Color", key: "63922aac4ff08f52d71fa891", children: [{ title: "Black", key: "Black-9e994ed2-823b-d1d6-4613-91d43f570fec" }, { title: "White", key: "White-5d0b102a-2555-8f7c-d471-cc82a5bd9c01" }] }] }, { title: "Elements", key: "5e69dbd7-5fee-67a9-c73f-4656f9b90715", children: [{ title: "Non metals", key: "633ac872e78fa7ebee03b8bf", children: [{ title: "Carbon", key: "Carbon-e443daa4-def4-9830-796e-ee8c5a1f41d4" }, { title: "Nitrogen", key: "Nitrogen-c2922569-0b2d-0e07-454d-d8411af701b7" }, { title: "Oxygen", key: "Oxygen-a3b8be32-c36e-a02e-37f4-a35239e0cedb" }] }] }, { title: "Planets", key: "33a3182b-93a4-84b9-4c49-c955a8416197", children: [{ title: "Composition", key: "63b3d5cd12c06ba7ce353f76", children: [{ title: "Chthonian planet", key: "Chthonian planet-b3c593c1-d29e-5e14-1b11-2241e8ef2be6" }, { title: "Carbon planet", key: "Carbon planet-07d67d62-afcf-fbcf-a8e8-75081cb44c2f" }] }] }],
remove = keys => {
const fn = array => {
let i = array.length;
while (i--) {
if (keys.includes(array[i].key)) array.splice(i, 1);
else if (array[i].children) fn(array[i].children);
}
};
return fn;
};
remove(keys)(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
given a tree-structured data, get the max height of the tree. i wanna get the max depth of a not-certain tree. the tree looks like below:
{
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true
}]
}]
}
i tried as below, but it did not work as expected.
const maxDepth = o => {
if(!o || !o.children) return 0;
let arr = []
for(let i = 0; i< o.children.length; i++) {
arr[i] = maxDepth(o.children[i])
}
let max = Math.max(...[arr]) + 1
return max
}
I don't believe your data is formatted 100% correctly, so I took the liberty of doing so. That being said, this screams for a recursive algorithm.
{
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true
}]
}]
}]
}
test1 = {
id: 1,
label: "test1",
children: []
}
test2 = {
id: 2,
label: "test1",
children: [
{
id: 2,
label: "test2",
children: []
},
{
id: 2,
label: "test2",
children: []
}]
}
test3 = {
id: 3,
label: "test1",
children: [
{
id: 3,
label: "test2",
children: [{
children: [{
children: [{}]
}]
}]
},
{
id: 3,
label: "test2",
children: [{}]
}]
}
your_data = {
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true
}]
}]
}]
}
my_data = {
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
},
{
id: 5,
label: 'label4',
disabled: true
}]
}]
},
{
id: 6,
label: 'madeup1',
children: [{
id: 7,
label: 'madeup2',
children: [{
id: 8,
label: 'madeup3',
children: [{
id: 9,
label: 'madeup4'
}]
}]
}]
}]
}
function max_depth(exploringTheDepthsOf)
{
largest = 0;
if (exploringTheDepthsOf.hasOwnProperty('children'))
{
for (var i = 0; i < exploringTheDepthsOf["children"].length; i++)
{
largest = Math.max(largest, max_depth(exploringTheDepthsOf["children"][i]));
}
}
else
{
return 0;
}
return largest + 1;
}
console.log("returned value", max_depth(test1));
console.log("returned value", max_depth(test2));
console.log("returned value", max_depth(test3));
console.log("returned value", max_depth(your_data));
console.log("returned value", max_depth(my_data));
This is about as close as I could get. Geeks for geeks has a pretty good artical on it and javascript code to show you how to do it, but its for actual nodes, not for json like objects: https://www.geeksforgeeks.org/depth-n-ary-tree/
I have an array of objects that I want to filter by comparing a nested property to a search term.
For example:
let array = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
},
{
category: 2,
label: "Checkbox1",
diId: 193909,
children: [{ label: "datafound", value: "47d18sb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "045e8786-2165-4e1e-a839-99b1b0ceef57"
}
]
},
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 1,
label: "Empty",
toType: "String",
value: "ebedb43f-4c53-491f-8954-d030321845cd"
},
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
},
{
category: 5,
defaultValueType: 8,
label: "Current Username",
toType: "String",
value: "25f6b40a-33c7-4f17-b29d-99e8d1e4e33c"
},
{
category: 5,
defaultValueType: 9,
label: "Current Location",
toType: "Location",
value: "ed59da2f-318d-4599-9085-4d9d769a27d7"
}
]
},
{
category: 4,
label: "Fixed Value",
isFixed: true,
value: "28e90e3e-a20b-4499-9593-061a7d1e7bd6"
// as you can see there is no children in this object
}
]};
What I'm trying to achieve is if I search for 'nodata' for example my result should be
let array = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
}
]
}
];
Another option if I search for 'spa' my result should be
let array = [
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
}
]
}
];
I have been super confused and I decided to get some help. Thank you for your helps guys!
The following function should do the trick for you:
function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));
if (objHasSearchTerm && !obj.children) return [obj];
const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}
It recursively goes through the data array, looks for any entries that have the specified search term, and if so, places it into the newly constructed object. It will preserve the nested shape of the object, which may or may not be what is needed. Feel free to tweak the algorithm to your own needs.
let allData = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
},
{
category: 2,
label: "Checkbox1",
diId: 193909,
children: [{ label: "datafound", value: "47d18sb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "045e8786-2165-4e1e-a839-99b1b0ceef57"
}
]
},
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 1,
label: "Empty",
toType: "String",
value: "ebedb43f-4c53-491f-8954-d030321845cd"
},
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
},
{
category: 5,
defaultValueType: 8,
label: "Current Username",
toType: "String",
value: "25f6b40a-33c7-4f17-b29d-99e8d1e4e33c"
},
{
category: 5,
defaultValueType: 9,
label: "Current Location",
toType: "Location",
value: "ed59da2f-318d-4599-9085-4d9d769a27d7"
}
]
},
{
category: 4,
label: "Fixed Value",
isFixed: true,
value: "28e90e3e-a20b-4499-9593-061a7d1e7bd6"
// as you can see there is no children in this object
}
];
function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));
if (objHasSearchTerm && !obj.children) return [obj];
const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}
console.log('----- Search: nodata')
console.log(JSON.stringify(searchData(allData, 'nodata'), null, 2))
console.log('----- Search: spa')
console.log(JSON.stringify(searchData(allData, 'spa'), null, 2))
I am trying to return the array of all the intersected array elements.
I got 2 arrays.
The array from api and the filter condition array.
Array from api is this
let somethingList = [
{
id: 'PROD108',
name: 'Headsweats Mid Cap',
CustomFields: [
{
name: 'Brand',
value: 'Headsweats',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD109',
name: 'Performance Liberty City Cycling Cap',
CustomFields: [
{
name: 'Brand',
value: 'Performance',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD110',
name: 'Castelli Logo Bandana',
CustomFields: [
{
name: 'Brand',
value: 'Castelli',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD159',
name: 'Performance Classic Sleeveless Jersey',
CustomFields: [
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#4CAF50',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD160',
name: 'Schwinn Evolution IC Sleeveless Jersey',
CustomFields: [
{
name: 'Brand',
value: 'Schwinn',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#2196F3',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD161',
name: 'Performance Elite Short',
CustomFields: [
{
name: 'Brand',
value: 'Performance',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#000000',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD162',
name: 'Andiamo! Padded Cycling Brief',
CustomFields: [
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#808080',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD163',
name: 'Fox Mojave Glove',
CustomFields: [
{
name: 'Brand',
value: 'Fox',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#000000',
},
{
name: 'Test',
value: '0',
},
],
},
];
filter condition array.
let testingFilter = ['Fox', 'Performance'];
What I want to do is if the customfield value of array from api is intersected with testingFilter value
I want to push them into an array and return that new array.
But the code I written don't return an new array, What should I do to return a new array
let filteredProduct = [];
filteredProduct = _.filter(somethingList, (product) => {
if (testingFilter.length === 0) {
return somethingList;
} else {
// Here is the problem
return _.intersection(testingFilter, _.map(product.CustomFields, 'value'));
}
});
Expected Answer array
filteredProduct = [
{
id: 'PROD109',
name: 'Performance Liberty City Cycling Cap',
CustomFields: [
{
name: 'Brand',
value: 'Performance',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD161',
name: 'Performance Elite Short',
CustomFields: [
{
name: 'Brand',
value: 'Performance',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#000000',
},
{
name: 'Test',
value: '0',
},
],
},
{
id: 'PROD163',
name: 'Fox Mojave Glove',
CustomFields: [
{
name: 'Brand',
value: 'Fox',
},
{
name: 'Eco',
value: 'False',
},
{
name: 'Color',
value: '#000000',
},
{
name: 'Test',
value: '0',
},
],
},
]
The following line taken from your code:
_.map(product.CustomFields, 'value')
Here, you get an array of all the values's of the CustomFields, if we check if there is an item from testinFilter present in that array, we can use that as the _filter return statement like so:
let filteredProduct = [];
filteredProduct = _.filter(somethingList, (product) => {
const allCustomFields = _.map(product.CustomFields, 'value');
return allCustomFields.some(r => testingFilter.indexOf(r) >= 0);
});
// We could rewrite the same code as a one-liner without the extra const like so:
let filteredProduct = _.filter(somethingList, (product) => _.map(product.CustomFields, 'value').some(r => testingFilter.indexOf(r) >= 0));
Snippet:
let testingFilter = ['Fox', 'Performance'];
let somethingList = [{id: 'PROD108', name: 'Headsweats Mid Cap', CustomFields: [{name: 'Brand', value: 'Headsweats', }, {name: 'Eco', value: 'False', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD109', name: 'Performance Liberty City Cycling Cap', CustomFields: [{name: 'Brand', value: 'Performance', }, {name: 'Eco', value: 'False', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD110', name: 'Castelli Logo Bandana', CustomFields: [{name: 'Brand', value: 'Castelli', }, {name: 'Eco', value: 'False', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD159', name: 'Performance Classic Sleeveless Jersey', CustomFields: [{name: 'Eco', value: 'False', }, {name: 'Color', value: '#4CAF50', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD160', name: 'Schwinn Evolution IC Sleeveless Jersey', CustomFields: [{name: 'Brand', value: 'Schwinn', }, {name: 'Eco', value: 'False', }, {name: 'Color', value: '#2196F3', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD161', name: 'Performance Elite Short', CustomFields: [{name: 'Brand', value: 'Performance', }, {name: 'Eco', value: 'False', }, {name: 'Color', value: '#000000', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD162', name: 'Andiamo! Padded Cycling Brief', CustomFields: [{name: 'Eco', value: 'False', }, {name: 'Color', value: '#808080', }, {name: 'Test', value: '0', }, ], }, {id: 'PROD163', name: 'Fox Mojave Glove', CustomFields: [{name: 'Brand', value: 'Fox', }, {name: 'Eco', value: 'False', }, {name: 'Color', value: '#000000', }, {name: 'Test', value: '0', }, ], }, ];
let filteredProduct = _.filter(somethingList, (product) => {
const allCustomFields = _.map(product.CustomFields, 'value');
return allCustomFields.some(r => testingFilter.indexOf(r) >= 0);
});
console.log(filteredProduct);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
Result:
[
{
"id": "PROD109",
"name": "Performance Liberty City Cycling Cap",
"CustomFields": [
{
"name": "Brand",
"value": "Performance"
},
{
"name": "Eco",
"value": "False"
},
{
"name": "Test",
"value": "0"
}
]
},
{
"id": "PROD161",
"name": "Performance Elite Short",
"CustomFields": [
{
"name": "Brand",
"value": "Performance"
},
{
"name": "Eco",
"value": "False"
},
{
"name": "Color",
"value": "#000000"
},
{
"name": "Test",
"value": "0"
}
]
},
{
"id": "PROD163",
"name": "Fox Mojave Glove",
"CustomFields": [
{
"name": "Brand",
"value": "Fox"
},
{
"name": "Eco",
"value": "False"
},
{
"name": "Color",
"value": "#000000"
},
{
"name": "Test",
"value": "0"
}
]
}
]
You can do:
let somethingList = [ { id: 'PROD108', name: 'Headsweats Mid Cap', CustomFields: [ { name: 'Brand', value: 'Headsweats', }, { name: 'Eco', value: 'False', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD109', name: 'Performance Liberty City Cycling Cap', CustomFields: [ { name: 'Brand', value: 'Performance', }, { name: 'Eco', value: 'False', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD110', name: 'Castelli Logo Bandana', CustomFields: [ { name: 'Brand', value: 'Castelli', }, { name: 'Eco', value: 'False', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD159', name: 'Performance Classic Sleeveless Jersey', CustomFields: [ { name: 'Eco', value: 'False', }, { name: 'Color', value: '#4CAF50', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD160', name: 'Schwinn Evolution IC Sleeveless Jersey', CustomFields: [ { name: 'Brand', value: 'Schwinn', }, { name: 'Eco', value: 'False', }, { name: 'Color', value: '#2196F3', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD161', name: 'Performance Elite Short', CustomFields: [ { name: 'Brand', value: 'Performance', }, { name: 'Eco', value: 'False', }, { name: 'Color', value: '#000000', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD162', name: 'Andiamo! Padded Cycling Brief', CustomFields: [ { name: 'Eco', value: 'False', }, { name: 'Color', value: '#808080', }, { name: 'Test', value: '0', }, ], }, { id: 'PROD163', name: 'Fox Mojave Glove', CustomFields: [ { name: 'Brand', value: 'Fox', }, { name: 'Eco', value: 'False', }, { name: 'Color', value: '#000000', }, { name: 'Test', value: '0', }, ], }, ];
let testingFilter = ['Fox', 'Performance'];
let filteredProducts = somethingList.filter(p =>
Array.from(p.CustomFields.values()) // iterable to array
.map(({value}) => value)
.some(value => testingFilter.includes(value)))
console.log(filteredProducts)
I have the following object array:
var sizeList = [
{ id: 1, title:"Test1",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 2,title:"Test2",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 3,title:"Test3",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:true}]
}
]
I want to filter this list where Medium is True. I currently have this set up.
var specificSizes = _.filter(sizeList.type, { 'name': 'Medium', 'present': true })
This keeps returning an empty array. I also tried this:
specificSizes = _.filter(sizeList.type, function (type) {
return _.some(type, {'name': 'Medium', 'present':true})
});
With lodash, you could wrap the condition in the same structure for the test, as the original object.
_.filter(sizeList, { type: [{ name: 'Medium', present: true }] })
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = _.filter(sizeList, { type: [{ name: 'Medium', present: true }] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
In plain Javascript, you could use Array#filter for the outer array and check with Array#some if one condition met.
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = sizeList.filter(function (a) {
return a.type.some(function (b) {
return b.name === 'Medium' && b.present;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }