Json:( How to iterate this array of arrays using map function.. I have tried this.. In this.materialList => array i am getting only 1 st array of values 2nd and 3rd array values are getting undefined.. so i am not able to display in html.. )
subrecipes:[
subrecipematerials: [
"id": 1
"material_id": {
"id":1,
"title":"cookies"
}
],
[
"id": 2
material_id: {
"id":2,
"title":"cake"
}
]
subrecipeformulations: [
"id": 1,
"formula_id": {
"id":1,
"title":formula1
}
]
]
subrecipes:[
subrecipematerials: [
"id": 1
material_id: {
"id":1,
"title":"cookies"
}
],
[
"id": 2
material_id: {
"id":2,
"title":"cake"
}
]
subrecipeformulations: [
"id": 1,
"formula_id": {
"id":1,
"title":formula1
}
]
]
component.ts(I have tried this.. In this.materialList => array i am getting only 1 st array of values 2nd and 3rd array values are getting undefined.. so i am not able to display in html.. )
let subrecipeMaterials = this.data.subRecipes.map((item, index) => {
item = item.subrecipeMaterials[index]
return item
})
let tempMatList1 = this.group_By_Data(subrecipeMaterials, "sub_recipe_id")
let matSubrecipies = Object.keys(tempMatList1).map(data => tempMatList1[data])
this.filterMaterials(matSubrecipies)
this.subrecipies = matSubrecipies.map((data, index) => {
return {
matList: this.materialList[index],
formList: this.otherFormulationList[index],
subRec: (index + 1)
}
})
group_By_Data(arr, key) {
return arr.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
filterMaterials(matSubrecipies) {
this.materialList = matSubrecipies.map(sub => {
return sub.filter(mat => {
let checkmat_id = mat.material_id
if (!!checkmat_id) }
return mat.material_id
}
})
})
}
getMaterialListArray(i) {// this function used to display this array through html.. right now only i am getting 1st array..
return this.materialList[i]
}
Your data is not correct. I think it should be in the form:
{subrecipes:[{
subrecipematerials: [{
"id": 1,
"material_id": {
"id":1,
"title":"cookies"
},
},
{
"id": 2,
material_id: {
"id":2,
"title":"cake"
}
}],
subrecipeformulations: [{
"id": 1,
"formula_id": {
"id":1,
"title":"formula1"
}
}]
},
{
subrecipematerials: [{
"id": 1,
material_id: {
"id":1,
"title":"cookies"
}
},
{
"id": 2,
material_id: {
"id":2,
"title":"cake"
}
} ] ,
subrecipeformulations: [{
"id": 1,
"formula_id": {
"id":1,
"title":"formula1"
}
}]
}]
};
Also, the code item = item.subrecipeMaterials[index] should be item = item.subrecipematerials[index] (difference is M and m as it is case sensitive).
Related
I want to create a nested filter in js
when I filter my array primary data is affected and changed but I need preliminary data to remove filters
my js code :
let result = companies;
result.map((item, i) => {212
let rows = [...result[i].table.table_rows].filter((item3) => {
return Object.keys(item3).some(i => item3[i][key] === value[key]);
});
result[i].table.table_rows = [...rows];
return result[i];
});
arrayFilter(result);
my data is:
{
"companies": [
{
"company": {
"name": "company 1"
},
"table": {
"table_rows": [
{
"cells": {
"product_name": "prod1",
"pa_size": "12"
}
},
{
"cells": {
"product_name": "prod2",
"pa_size": "15"
}
}
]
}
},
{
"company": {
"name": "company 2"
},
"table": {
"table_rows": [
{
"cells": {
"product_name": "prod2-1",
"pa_size": "12"
}
},
{
"cells": {
"product_name": "prod2-2",
"pa_size": "18"
}
}
]
}
}
]
}
I tried many ways to solve this problem, but I did not get the right answer
Your question is not clear, the point I have understand that you wanted to filter the array "table_rows" located inside each companies array object? map and filter returns new array, so the solution for this is:
result = result.companies.map((item, i) => {
const newItem = {...item};
let rows = newItem .table.table_rows.filter((item3) => {
return Object.keys(item3).some(i => item3[i][key] === value[key]);
});
newItem.table_rows = [...rows];
return newItem ;
});
arrayFilter(result);
I have below array format:
[
{
"category": "c8kr0cv012vtr8vm3iqg",
"subcategories": [
"c8kr3d7012vtr8vm3jm0",
"c8kr3d7012vtr8vm3jlg",
"c8kr3d7012vtr8vm3jk0",
"c8kr8h7012vtr8vm3m5g",
"c8tjghovq0ahq4ccf980",
"c8kr3nn012vtr8vm3jog",
"c8kr3nn012vtr8vm3jo0",
"c8kr3nn012vtr8vm3jp0",
]
},
{
"category": "c8kr0cv012vtr8vm3ivg",
"subcategories": [
"c8kr3d7012vtr8vm3jm0",
"c8kr3d7012vtr8vm3jlg",
"c8kr3d7012vtr8vm3jk0",
"c8kr8h7012vtr8vm3m5g",
"c8tjghovq0ahq4ccf980",
"c8kr3nn012vtr8vm3jog",
"c8kr3nn012vtr8vm3jo0",
"c8kr3nn012vtr8vm3jp0",
]
},
{
"category": "c8kr0cv012vtr8vm3is0",
"subcategories": [
"c8kr3d7012vtr8vm3jm0",
"c8kr3d7012vtr8vm3jlg",
"c8kr3d7012vtr8vm3jk0",
"c8kr8h7012vtr8vm3m5g",
"c8kr3nn012vtr8vm3jog",
"c8kr3nn012vtr8vm3jo0",
"c8kr3nn012vtr8vm3jp0",
]
},
{
"category": "c8kr0cv012vtr8vm3ir0",
"subcategories": [
"c8kr3d7012vtr8vm3jm0",
"c8kr3d7012vtr8vm3jlg",
"c8kr3d7012vtr8vm3jk0",
"c8kr8h7012vtr8vm3m5g",
"c8tjghovq0ahq4ccf980",
"c8kr3nn012vtr8vm3jog",
"c8kr3nn012vtr8vm3jo0",
"c8kr3nn012vtr8vm3jp0",
]
}
]
I want to remove value from subcategory array for example c8tjghovq0ahq4ccf980
I tried below code:
tempPayload.some(function (a) {
return a.subcategories.some(function (b, i, bb) {
if (b === "c8tjghovq0ahq4ccf980") {
bb.splice(i, 1);
return true;
}
});
});
But it is not working any idea how can I resolve this?
Try with following code:
tempPayload.map((item) => {
const index = item.subcategories.indexOf("c8tjghovq0ahq4ccf980");
if (index > -1) {
item.subcategories.splice(index, 1);
}
});
for(let i=0; i<tempPayload.length; i++){
tempPayload[i].subcategories = tempPayload[i].subcategories.filter(i => i!== "c8tjghovq0ahq4ccf980")
}
console.log(tempPayload)
I have list of tree node metadataList Like below:
[
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
}
]
},
{
"data": {
"metadata": {
"category": [
"Isv"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Isv"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Isv"
]
}
},
"children": [
]
}
]
},
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
]
}
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Isv"
]
}
},
"children": [
]
}
]
},
{
"data": {
"metadata": {
"category": [
"Incentives"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Incentives"
]
}
},
"children": [
]
}
]
}
]
Which is a type of array of data and children collection it's class like below:
export default class CurrentTopicMetadataTreeNode {
public data: CurrentTopicMetadata;
public children: CurrentTopicMetadataTreeNode[];
}
export default class CurrentTopicMetadata {
public id: string;
public metadata: TopicMetadata
}
export class TopicMetadata {
public category: Category[]
}
export enum Category {
Csp = 'Csp',
Mpn = 'Mpn',
Incentives = 'Incentives',
Referrals = 'Referrals',
Isv = 'Isv',
}
What I am trying, to filter list as data and children order as per category. Let say if filter by a category all data and children belongs to that category should come like below order.
But I am getting data like this order :
One Element On Array Problem Set:
Here in this array if I search with Csp Only data in root node which is Csp and data in children only has one data which contains Csp would be in array.
[{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
},
{
"data": {
"metadata": {
"category": [
"Mpn"
]
}
},
"children": [
]
}
]
}]
Expected Output: So after filtered by Csp node should be look like this:
[
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
{
"data": {
"metadata": {
"category": [
"Csp"
]
}
},
"children": [
]
}
]
}
]
here is my code, where I am doing wrong?
// Rule 1 check parent metadata category whether be empty
// Rule 2 and 3
function find_in_children(children, parent_category) {
children_has_same_category = []
for(var i in children) {
let child = children[i];
if(child.children != undefined && child.children.length > 0 && child.data.metadata.category == parent_category) {
children_has_same_category.push(child);
}
}
if(children_has_same_category.length > 0) {
return children_has_same_category
} else {
for(var i in children) {
let child = children[i];
return find_in_children(child.children, parent_category);
}
}
}
function check_object(object) {
let parent_category = object.data.metadata.category[0];
if(object.children != undefined && object.children.length > 0) {
return {'data': object.data, 'children': find_in_children(object.children, parent_category)}
} else {
return {'data': object.data}
}
}
function apply_rules(object) {
// Rule 1 check parent metadata category whether be empty
if(object.data.metadata.category.length > 0) {
return {'data': object.data}
} else {
return check_object(object)
}
}
target = {
value: 'Isv'
}
filtered_datas = []
for(var i in datas) {
let data = datas[i];
if(data.data.metadata.category.length > 0) {
result = apply_rules(data)
if(result.data.metadata.category[0] == target.value) {
filtered_datas.push(result);
}
}
}
Here is the data sample and result: https://jsfiddle.net/faridkiron/b02cksL8/#&togetherjs=F7FK3fBULx
Another Recursive Function I have tried:
handleRecursiveParentChildNode(parent: CurrentTopicMetadataTreeNode, searchKey) {
let result = parent;
result.children = [];
if (parent.children.length > 0) {
parent.children.forEach(child => {
let childData = this.handleRecursiveParentChildNode(child, searchKey);
if (childData.data && childData.data != undefined)
result.children.push(childData);
});
let cate = parent.data.metadata.category.filter(cat => cat === searchKey);
if (!result.children && cate.length < 1) {
result = null;
}
}
else {
let cate = parent.data.metadata.category.filter(cat => cat === searchKey);
if (cate.length < 1) {
result = null;
}
}
return result;
}
You can filter the data with Array.prototype.filter
const data = [{"data":{"metadata":{"category":["Csp"]}},"children":[{"data":{"metadata":{"category":["Csp"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]}]},{"data":{"metadata":{"category":["Isv"]}},"children":[{"data":{"metadata":{"category":["Isv"]}},"children":[]},{"data":{"metadata":{"category":["Isv"]}},"children":[]}]},{"data":{"metadata":{"category":["Csp"]}},"children":[{"data":{"metadata":{"category":["Csp"]}},"children":[]}]},{"data":{"metadata":{"category":["Mpn"]}},"children":[{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Csp"]}},"children":[]},{"data":{"metadata":{"category":["Isv"]}},"children":[]}]},{"data":{"metadata":{"category":["Incentives"]}},"children":[{"data":{"metadata":{"category":["Incentives"]}},"children":[]}]}]
const dfs = (iNode, type) => {
const node = Object.assign({}, iNode) // shallow copy current node
node.children = iNode.children.flatMap(child => {
// if child matches type, return it, otherwise filter it out
return child.data.metadata.category.includes(type) ? dfs(child, type) : []
})
return node
}
// fakes a root node to apply dfs on
const cspList = dfs({ children: data }, 'Csp').children
console.log(JSON.stringify(cspList, null, 2))
edit: in case flatMap can't be used (for some reasons) it is possible to use filter + map
const data = [{"data":{"metadata":{"category":["Csp"]}},"children":[{"data":{"metadata":{"category":["Csp"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]}]},{"data":{"metadata":{"category":["Isv"]}},"children":[{"data":{"metadata":{"category":["Isv"]}},"children":[]},{"data":{"metadata":{"category":["Isv"]}},"children":[]}]},{"data":{"metadata":{"category":["Csp"]}},"children":[{"data":{"metadata":{"category":["Csp"]}},"children":[]}]},{"data":{"metadata":{"category":["Mpn"]}},"children":[{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Mpn"]}},"children":[]},{"data":{"metadata":{"category":["Csp"]}},"children":[]},{"data":{"metadata":{"category":["Isv"]}},"children":[]}]},{"data":{"metadata":{"category":["Incentives"]}},"children":[{"data":{"metadata":{"category":["Incentives"]}},"children":[]}]}]
const dfs = (iNode, type) => {
const node = Object.assign({}, iNode) // shallow copy current node
node.children = iNode.children
.filter(child => child.data.metadata.category.includes(type))
.map(child => dfs(child, type))
return node
}
// fakes a root node to apply dfs on
const cspList = dfs({ children: data }, 'Csp').children
console.log(JSON.stringify(cspList, null, 2))
regarding errors in original code
handleRecursiveParentChildNode(parent: CurrentTopicMetadataTreeNode, searchKey) {
let result = parent;
result.children = [];
// bug? since we are called from parent we obviously are a children
// so else block is never run
if (parent.children.length > 0) {
parent.children.forEach(child => {
let childData = this.handleRecursiveParentChildNode(child, searchKey);
// bug ? we never filter out children and push every one of them on result
if (childData.data && childData.data != undefined)
result.children.push(childData);
});
// bug ? !result.children is never truthy (![] === false)
// so if is never run
let cate = parent.data.metadata.category.filter(cat => cat === searchKey);
if (!result.children && cate.length < 1) {
result = null;
}
}
// never run
else {
let cate = parent.data.metadata.category.filter(cat => cat === searchKey);
if (cate.length < 1) {
result = null;
}
}
return result;
}
You can use recursive call reduce for filter your data:
const filterItems = (items, f) => {
const fitems = items.reduce((acc, rec) => {
const children = rec.children.length > 0 ? filterItems(rec.children, f): []
if (rec.data.metadata.category.indexOf(f) >= 0) {
return [...acc, {...rec, children}]
}
return [...acc]
}, [])
return fitems
}
I'm trying to filter an nested array of objects but it's not working as expected....
Here is my json:
[
{
"seasson_number": "1",
"episodes": [
{
"number": 1,
"video_url": "http://test.com",
"name": "Testing"
},
{
"number": 2,
"video_url": "http://test.com",
"name": "Testing"
}
]
},
{
"seasson_number": "2",
"episodes": [
{
"number": 1,
"video_url": "http://test.com",
"name": "Testing"
},
{
"number": 2,
"video_url": "http://test.com",
"name": "Testing"
}
]
}
]
And this is my function to filter by the seasson_number and get the episode name:
const episodios = this.state.seassons
.filter(seasson => {
return seasson.seasson_number === "2"; // sample number
})
.map(seasson => {
seasson.episodes.map(episode =>{
return (
<h2>{episode.name}</h2>
)
})
});
In your first map function, you should add a return statement:
map(seasson => {
return seasson.episodes.map(episode =>{
return (
<h2>{episode.name}</h2>
)
})
});
I am trying to return all objects that have a specific 'id' in the nested array. In the sample data, I'd like to return all person objects with hobbies id of 2 (hiking).
The other question addresses the problem of finding all values in an array based on an object value.
This question differs from the previous because I need to return all objects based on a value inside of a nested array.
[
{
"id":111222,
"name":"Faye",
"age":27,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":3,
"name":"eating"
}
]
},
{
"id":223456789001,
"name":"Bobby",
"age":35,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":4,
"name":"online gaming"
}
]
}
]
function hasHobby(person, hobbyId) {
return person.hobbies.some(function(hobby) {
return hobby.id === hobbyId;
});
}
function filterByHobby(people, hobbyId) {
return people.filter(function(person) {
return hasHobby(person, hobbyId);
});
}
If you wanna use the new cool ES6 syntax:
function filterByHobby(people, hobbyId) {
return people.filter(
person => person.hobbies.some(
hobby => hobby.id === hobbyId
)
);
}
var arr = [
{
"id":111222,
"name":"Faye",
"age":27,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":3,
"name":"eating"
}
]
},
{
"id":223456789001,
"name":"Bobby",
"age":35,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":4,
"name":"online gaming"
}
]
}
];
arr.filter(function(obj) {
var hobbies = obj.hobbies;
var x = hobbies.filter(function(hob) {
if (hob.id == "2") return true;
});
if (x.length > 0) return true;
});
Try this, I think its solve your proble:
var arr = [{
"id": 111222,
"name": "Faye",
"age": 27,
"hobbies": [{
"id": 2,
"name": "hiking"
}, {
"id": 3,
"name": "eating"
}]
}, {
"id": 223456789001,
"name": "Bobby",
"age": 35,
"hobbies": [{
"id": 2,
"name": "hiking"
}, {
"id": 4,
"name": "online gaming"
}]
}];
var x = arr.filter(function(el) {
var rnel = el.hobbies.filter(function(nel) {
return nel.id == 2;
});
return rnel.length > 0 ? true :false;
});
alert(x.length);