Related
Javascript
I have a nested array of objects, I'm trying to filter the given array of objects using a property from the third level of its array property value. For example, from the below array I like to filter the entire array using the property ListId: 10
Example
let test = {
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":11,
"name":"string2",
"state":"BY"
},
{
"ListId":12,
"name":"string3",
"state":"BY"
}
]
}
]
},
{
"name":"header2",
"value":[
{
"id":"01",
"list":[
{
"ListId":100,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":111,
"name":"string2",
"state":"BY"
},
{
"ListId":121,
"name":"string3",
"state":"BY"
}
]
}
]
}
]
}
Filtervalue with ListId = 10
Expected output :
{
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
}
]
}
]
}
]
}
How can I use the filter method using javascript to get this expected result?
You can two it in two times :
First, filter the list arrays,
Secondly filter the groups array using the some method
let test= {
"test": true,
"group": [
{
"name": "header",
"value": [
{
"id": "0",
"list": [
{
"ListId": 10,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 11,
"name": "string2",
"state": "BY"
},
{
"ListId": 12,
"name": "string3",
"state": "BY"
}
]
}
]
},
{
"name": "header2",
"value": [
{
"id": "01",
"list": [
{
"ListId": 100,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 111,
"name": "string2",
"state": "BY"
},
{
"ListId": 121,
"name": "string3",
"state": "BY"
}
]
}
]
}
]
}
test.group.forEach(group => {
group.value.forEach(value => {
value.list = value.list.filter(list => list.ListId === 10)
})
})
test.group = test.group.filter(group => group.value.some(value => value.list.length > 0))
console.log(test)
Note : You should use plural names for you arrays, it helps understanding the data. For example lists not list for the array.
let z ={"group1": [
{
"name": "header",
"value": [
{
"id": 0,
"list": [
{
"ListId": 10,
"Name": "string1"
},
{
"ListId": 11,
"Name": "string2"
}
]
}
]
}
]}
// This function was written from understading that 'group1' is not a fixed property, but part of a dynamic list due to the number '1'
const getItemByListId = (list, listId) => {
const listKeys = Object.keys(list);
const selectedListKey = listKeys.find(key => {
const groupItems = list[key];
const selectedItem = groupItems.find(({ value: nestedItems }) => {
const selectedNestedItem = nestedItems.find(({ list }) => {
const selectedList = list.find(({ ListId }) => ListId === listId)
return selectedList;
});
return selectedNestedItem;
});
return selectedItem;
});
if (!selectedListKey) {
return null;
}
return list[selectedListKey];
};
console.log(getItemByListId(z, 10));
In this array children array can have more childrens. I have a method in which I will get "lowValue" and "highValue". "Id" will be unique. when my method get called I need to use this unique id and replace old values of "lowValue" and "highValue" with the new ones. How can I do that?
// put your code here
<script>
myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
]
</script>
Simple
const data = your_original_data
function replacer(lowValue, highValue, id){
for(let i = 0; i < data.length; i++){
for(let j = 0; j < data[i].children.length; j++){
if(data[i].children[j].data.id === id){
data[i].children[j].data.lowValue = lowValue
data[i].children[j].data.highValue = highValue
return
}
}
}
}
const myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
]
const indexMap = new Map()
const parseDataToMap = (data = []) => {
data.forEach(e => {
if (e.children) {
e.children.forEach(e => {
indexMap.set(e.data.id, e.data)
})
}
})
}
parseDataToMap(myData)
console.log(myData[0].children[0].data)
const o = indexMap.get(1)
o.highValue = 25
o.lowValue = 11
console.log(myData[0].children[0].data)
Given the below-mentioned assumptions:
All children where id matches the supplied value will have the lowValue and highValue replaced.
The supplied id will always be present in the myData array in one or more children.
the following is one possible solution to achieve the desired result:
const replaceValues = (id = 5, lv = 5, hv = 50, arr = myData) => (
arr.reduce((f, i) => [...f, {
...i,
children: i.children.map(
child => ({
...child,
data: {
...child.data,
...(
child.data.id === id ? {
lowValue: lv,
highValue: hv
} : {}
)
}
})
)
}], [])
);
Explanation / Approach
The outer .reduce helps to iterate through the myData array
Each element in this array is placed as-is (using the ... spread operator)
Next, the children prop of each myData element is specified
Within this, i.children array is iterated using map to access each element
Each element here (again) is placed as-is using the ... spread-operator
Next, data is specified
Values for the data object are also spread (as before)
Then, if the data.id matches the parameter id then, lowValue and highValue are updated (using parameters lv and hv, respectively)
The ...( some_condition ? {k: v} : {} ) is one way to update an object's specific prop/s only when some_condition is true
Please use comments below to ask for further clarification/s.
Code Snippet
const myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
];
const replaceValues = (id = 5, lv = 5, hv = 50, arr = myData) => arr.reduce((f, i) => [...f, {
...i,
children: i.children.map(
child => ({
...child,
data: {
...child.data,
...(
child.data.id === id ? {
lowValue: lv,
highValue: hv
} : {}
)
}
})
)
}], []);
console.log('replace id: 5, low: 5, high: 50', replaceValues());
console.log('replace id: 1, low: 11, high: 21', replaceValues(1, 11, 21));
Hi I am getting data from API but I want my data in different format so that I can pass later into a function. I want to change the names of keys into a different one becasuse I have created a chart and it only draws if I send it data in certain way
This is what I am getting from API
data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [
{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
But I want my data to look like this like this
data = {
"name": "KSE100",
"children": [
{
"name": "A",
'points': -9,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
Like I want to replace
stock_sector_name = name
sector_score = value
stocks = children
stock_symbol = name
stock_score = value
I have been trying this for so much time but sill could not figured it out
function convert(d){
return {
name : d.indice,
children : d.data.map(y=>{
return {
name : y.stock_sector_name,
points : y.sector_score,
children : y.stocks.map(z=>{
return {
stock_title: z.stock_symbol,
value : z.stock_score
}
})
}
})
}
}
You can do something like this
const data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
const data2 = {
"name": "KSE100",
"children": [{
"name": "A",
'points': -9,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
//stock_sector_name = name
//sector_score = value
//stocks = children
//stock_symbol = stock_title
//stock_score = value
const keys = {
stock_sector_name: "name",
sector_score: "points",
stocks: "children",
stock_symbol: "stock_title",
stock_score: "value",
indice: "name",
//data: "children"
}
const rename = (value) => {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map(rename);
return Object.fromEntries(Object
.entries(value)
.map(([k, v]) => [keys[k] || k, rename(v)])
);
}
renamedObj = rename(data);
console.log(renamedObj);
I have an array of conversation between two entities, each distinguished based on parent and level. Every request will be followed by a response object. The sample input structure is like below
[
{ "message": "one", "messageSequence": 0, "level": 1, "Parent": "", "messageType": "request" },
{ "message": "two", "messageType": "response", "messageSequence": 1 },
{ "message": "three-1 (3.1)", "messageSequence": 2, "level": 2, "Parent": 1, "messageType": "request" },
{ "message": "four", "messageType": "response", "messageSequence": 3 },
{ "message": "five-1 (5.1)", "messageSequence": 4, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "six", "messageType": "response", "messageSequence": 5 },
{ "message": "five-2 (5.2)", "messageSequence": 6, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "seven", "messageType": "response", "messageSequence": 7 },
{ "message": "three-2 (3.2)", "messageSequence": 8, "level": 2, "Parent": 1, "messageType": "request" },
{ "message": "eight", "messageType": "response", "messageSequence": 9 },
{ "message": "nine-1 (9.1)", "messageSequence": 10, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "ten", "messageType": "response", "messageSequence": 11 },
{ "message": "nine-2 (9.2) ", "messageSequence": 12, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "eleven", "messageType": "response", "messageSequence": 13 }
]
I am trying to generate a json based on request and its corresponding response. Below is the method which I am using to achieve it
var prevLevel;
var lastUserItem = 0;
function convertToJson(array) {
var map = {};
for (var i = 0; i < array.length; i++) {
var obj = array[i];
if (array[i].messageType == "request")
obj.request = [];
else
obj.response = {};
if (obj.level) {
prevLevel = obj.level
map[obj.level] = obj;
var parent = obj.Parent || '-';
if (!map[parent]) {
map[parent] = {
request: []
};
}
delete obj.Parent;
delete obj.level;
delete obj.messageType;
delete obj.messageSequence;
map[parent].request.push(obj);
lastUserItem = map[parent].request.length - 1;
} else {
delete obj.Parent;
delete obj.level;
delete obj.messageType;
delete obj.messageSequence;
if (map[prevLevel].request && map[prevLevel].request.length > 0) {
map[prevLevel].request[lastUserItem].response = {};
map[prevLevel].request[lastUserItem].response = obj;
} else {
map[prevLevel].response = {};
map[prevLevel].response = obj;
}
}
}
return map['-'].request;
}
var r = convertToJson(messages);
console.log(JSON.stringify(r));
The response which I am getting is not structured based on the request entity.
Response from the above method
[
{
"message": "one",
"request": [
{
"message": "three-1 (3.1)",
"request": [
{
"message": "five-1 (5.1)",
"request": [],
"response":
{
"message": "six",
"response":
{}
}
},
{
"message": "five-2 (5.2)",
"request": [],
"response":
{
"message": "seven",
"response":
{}
}
}],
"response":
{
"message": "four",
"response":
{}
}
},
{
"message": "three-2 (3.2)",
"request": [
{
"message": "nine-1 (9.1)",
"request": [],
"response":
{
"message": "ten",
"response":
{}
}
},
{
"message": "nine-2 (9.2) ",
"request": [],
"response":
{
"message": "eleven",
"response":
{}
}
}],
"response":
{
"message": "eight",
"response":
{}
}
}],
"response":
{
"message": "two",
"response":
{}
}
}]
The Response objects are getting seperated. The expected json output is like below
{
"request": [{
"message": "one",
"response": {
"message": "two"
"request": [{
"message": "three-1 (3.1)",
"response": {
"message": "four"
"request": [{
"message": "five-1 (5.1)",
"response": {
"message": "six"
}
},
{
"message": "five-2 (5.2)",
"response": {
"message": "seven"
}
}
]
}
},
{
"message": "three-2 (3.2)",
"response": {
"message": "eight",
"request": [{
"message": "nine-1 (9.1)",
"response": {
"message": "ten"
}
},
{
"message": "nine-2 (9.2) ",
"response": {
"message": "eleven"
}
}
]
}
}
]
}
}]
}
Please suggest where I am going wrong. Anything to change in the input structure to get the desired output.
https://jsfiddle.net/49qLhL8g/4/
If the 'response' type is always directly coming after 'request', then you could build a new object with a look ahead to the next object and insert this message into the new object as result.
This proposal uses an array for the level reference and updates the levels in that array and as well as in the result.
var data = [{ message: "one", messageSequence: 0, level: 1, Parent: "", messageType: "request" }, { message: "two", messageType: "response", messageSequence: 1 }, { message: "three-1 (3.1)", messageSequence: 2, level: 2, Parent: 1, messageType: "request" }, { message: "four", messageType: "response", messageSequence: 3 }, { message: "five-1 (5.1)", messageSequence: 4, level: 3, Parent: 2, messageType: "request" }, { message: "six", messageType: "response", messageSequence: 5 }, { message: "five-2 (5.2)", messageSequence: 6, level: 3, Parent: 2, messageType: "request" }, { message: "seven", messageType: "response", messageSequence: 7 }, { message: "three-2 (3.2)", messageSequence: 8, level: 2, Parent: 1, messageType: "request" }, { message: "eight", messageType: "response", messageSequence: 9 }, { message: "nine-1 (9.1)", messageSequence: 10, level: 3, Parent: 2, messageType: "request" }, { message: "ten", messageType: "response", messageSequence: 11 }, { message: "nine-2 (9.2) ", messageSequence: 12, level: 3, Parent: 2, messageType: "request" }, { message: "eleven", messageType: "response", messageSequence: 13 }],
result = [],
levels = [result];
data.forEach(function (o, i, a) {
var level = o.level - 1, temp;
if (o.messageType !== 'request') {
return;
}
temp = { message: o.message, response: { message: a[i + 1].message, request: [] } };
levels[level + 1] = temp.response.request;
levels[level].push(temp);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I tried to do it using lodash in a very complex way as below .
var _lodash = require('lodash');
var arrayTwo = [
{ "message": "one", "messageSequence": 0, "level": 1, "Parent": "", "messageType": "request" },
{ "message": "two", "messageType": "response", "messageSequence": 1, "Parent": 0 },
{ "message": "three-1 (3.1)", "messageSequence": 2, "level": 2, "Parent": 1, "messageType": "request" },
{ "message": "four", "messageType": "response", "messageSequence": 3, "Parent": 2 },
{ "message": "five-1 (5.1)", "messageSequence": 4, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "six", "messageType": "response", "messageSequence": 5, "Parent": 3 },
{ "message": "five-2 (5.2)", "messageSequence": 6, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "seven", "messageType": "response", "messageSequence": 7, "Parent": 3 },
{ "message": "seven-1 (7.1)", "messageSequence": 8, "level": 4, "Parent": 3, "messageType": "request" },
{ "message": "seven-2 (7.2)", "messageType": "response", "messageSequence": 9, "Parent": 4 },
{ "message": "three-2 (3.2)", "messageSequence": 10, "level": 2, "Parent": 1, "messageType": "request" },
{ "message": "eight", "messageType": "response", "messageSequence": 11, "Parent": 2 },
{ "message": "nine-1 (9.1)", "messageSequence": 12, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "ten", "messageType": "response", "messageSequence": 13, "Parent": 3 },
{ "message": "nine-2 (9.2) ", "messageSequence": 14, "level": 3, "Parent": 2, "messageType": "request" },
{ "message": "eleven", "messageType": "response", "messageSequence": 15, "Parent": 3 }
];
var finalObj = {};
for (var i = 0; i < arrayTwo.length; i++) {
if (arrayTwo[i].messageType == "request") {
findAndAppendToRequest(arrayTwo[i]);
} else {
findAndAppendToResponse(arrayTwo[i]);
}
}
console.log(JSON.stringify(finalObj));
function findAndAppendToResponse(item) {
var parent = item.Parent;
var res = findBotNode();
var dt = _lodash.get(finalObj, res);
if (dt) {
if (!_lodash.has(finalObj, res + ".response")) {
_lodash.set(finalObj, res + ".response", {});
}
var data = {};
data.message = item.message;
_lodash.set(finalObj, res + ".response", data);
}
function findBotNode() {
var t = "";
if (parent == 0) {
t = 'request[' + 0 + ']';
} else {
for (var i = 0; i < parent; i++) {
if (!t) {
t = 'request[' + i + ']';
} else {
var temp = t + '.response.request[' + i + ']';
var cnt = 1;
while (!checkIfExists(temp)) {
temp = "";
var val = i - cnt;
temp = t + '.response.request[' + val + ']';
cnt++;
}
t = temp;
}
}
}
return t;
}
}
function checkIfExists(val) {
return _lodash.get(finalObj, val);
}
function findAndAppendToRequest(item) {
var msg = {};
msg.message = item.message;
if (!finalObj.request) {
finalObj.request = [];
finalObj.request.push(msg);
} else {
var parent = item.Parent;
var res = traverseNode();
var dt = _lodash.get(finalObj, res);
if (dt) {
if (!_lodash.has(finalObj, res + ".request")) {
_lodash.set(finalObj, res + ".request", []);
}
var ob = _lodash.get(finalObj, res + ".request");
ob.push(msg);
_lodash.set(finalObj, res + ".request", ob);
}
function traverseNode() {
var t = "";
for (var i = 0; i < parent; i++) {
if (!t) {
t = 'request[' + i + '].response';
} else {
var temp = t + '.request[' + i + '].response';
var cnt = 1;
while (!checkIfExists(temp)) {
temp = "";
var val = i - cnt;
temp = t + '.request[' + val + '].response';
cnt++;
}
t = temp;
}
}
return t;
}
}
}
Not sure if it work for all scenerios . #Nina Scholz great answer.
Category JSON
I am getting this JSON by accessing API and soring it in $scope.categoryList
[
{
"id": 1,
"name": "Men"
},
{
"id": 2,
"name": "Women"
},
{
"id": 3,
"name": "Kids"
}
]
SubCategory JSON
I am getting this JSON by accessing API and soring it in $scope.subCategoryList
[
{
"id": 1,
"category_id": 1,
"name": "Footwear"
},
{
"id": 2,
"category_id": 2,
"name": "Footwear"
},
{
"id": 3,
"category_id": 1,
"name": "Cloths"
}
]
I need to design this in below format
[
{
"categoryId" : 1,
"categoryName" : "Men",
"subCategory" : [
{
"subCategoryId": 1,
"subCategoryName": "Footwear"
},
{
"subCategoryId": 3,
"subCategoryName": "Cloths"
},
]
},
{
"categoryId" : 2,
"categoryName" : "Women",
"subCategory" : [
{
"subCategoryId": 2,
"subCategoryName": "Footwear"
}
]
},
{
"categoryId" : 3,
"categoryName" : "Kids",
"subCategory" : []
}
]
I have the code but it is not showing perfect data
$scope.catSubCat = []
angular.forEach($scope.subcategoryList, function(subValue, subKey) {
$scope.subCat = {
'subCategoryId' : '',
'subCategoryName' : ''
}
angular.forEach($scope.categoryList, function(catValue, catKey) {
if(subValue.category_id == catValue.id) {
$scope.subCat.subCategoryId = subValue.id;
$scope.subCat.subCategoryName = subValue.name;
$scope.subCategory = {
'categoryId' : '',
'categoryName' : '',
'subCatName' : []
}
$scope.catVal.categoryId = subValue.category_id;
$scope.catVal.categoryName = catValue.name;
$scope.catVal.subCatName.push($scope.subCat);
}
$scope.catSubCat.push($scope.catVal);
});
});
This should do the trick. Not as clean as 31piy's (wow!) but more efficient. (O(N + M) as opposed to O(N * M))
const categoryList = [
{
"id": 1,
"name": "Men"
},
{
"id": 2,
"name": "Women"
},
{
"id": 3,
"name": "Kids"
}
];
const subCategoryList = [
{
"id": 1,
"category_id": 1,
"name": "Footwear"
},
{
"id": 2,
"category_id": 2,
"name": "Footwear"
},
{
"id": 3,
"category_id": 1,
"name": "Cloths"
}
];
const mergeCategoryLists = (categoryList, subCategoryList) => {
// Turn categoryList into an object with categoryId as key
const categoryById = {};
categoryList.forEach((category) => {
categoryById[category.id] = {
categoryName: category.name,
categoryId: category.id,
subCategory: []
};
});
// Add subcategories
subCategoryList.forEach((subCategory) => {
const formattedSubCategory = {
subCategoryId: subCategory.id,
subCategoryName: subCategory.name
};
categoryById[subCategory.category_id].subCategory.push(formattedSubCategory);
});
// Convert categoryById into desired format
return Object.values(categoryById);
};
console.log(mergeCategoryLists(categoryList, subCategoryList));
Check out this logic .
$scope.newArray = angular.copy($scope.categoryList);
$scope.catSubCat = []
angular.forEach($scope.subcategoryList, function(subValue, subKey) {
$scope.subCat = {
'subCategoryId' : '',
'subCategoryName' : ''
}
angular.forEach($scope.newArray, function(catValue, catKey) {
$scope.subCat.subCategoryId = subValue.id;
$scope.subCat.subCategoryName = subValue.name;
if(subValue.category_id == catValue.id) {
if(catValue.subCatName.hasOwnProperty('bye')){
$scope.newArray[catKey].subCatName = [];
$scope.newArray[catKey].subCatName.push($scope.subCat);
}else{
$scope.newArray[catKey].subCatName.push($scope.subCat);
}
}
});
});
Resultant will we in $scope.newArray
You can use Array#map in combination with Array#filter to achieve the desired results:
var categories = [{
"id": 1,
"name": "Men"
},
{
"id": 2,
"name": "Women"
},
{
"id": 3,
"name": "Kids"
}
];
var subcategories = [{
"id": 1,
"category_id": 1,
"name": "Footwear"
},
{
"id": 2,
"category_id": 2,
"name": "Footwear"
},
{
"id": 3,
"category_id": 1,
"name": "Cloths"
}
];
var result = categories.map(cat => {
return {
categoryId: cat.id,
categoryName: cat.name,
subCategory: subcategories
.filter(subc => subc.category_id === cat.id)
.map(subc => {
return {
subCategoryId: subc.id,
subCategoryName: subc.name
};
})
};
});
console.log(result);
var categoryList = [{
"id": 1,
"name": "Men"
}, {
"id": 2,
"name": "Women"
}, {
"id": 3,
"name": "Kids"
}];
var subCategoryList = [{
"id": 1,
"category_id": 1,
"name": "Footwear"
}, {
"id": 2,
"category_id": 2,
"name": "Footwear"
}, {
"id": 3,
"category_id": 1,
"name": "Cloths"
}];
var finalJson = [];
for (var i = 0; i < categoryList.length; i++) {
var obj = {
categoryId: categoryList[i].id,
categoryName: categoryList[i].name,
subCategory: []
};
var subCat = subCategoryList.filter(function(word) {
return word.category_id === categoryList[i].id;
});
for (var j = 0; j < subCat.length; j++) {
var obj2 = {
subCategoryId: subCat[j].id,
subCategoryName: subCat[j].name
};
obj.subCategory.push(obj2);
}
finalJson.push(obj);
}
console.log(finalJson);
Pure Javascript solution to your question, you can replace with
Angular Syntax then..
Use following code:
$scope.catSubCat = []
angular.forEach($scope.categoryList, function(catValue, catKey) {
var catObj = {
'categoryId' : '',
'categoryName' : '',
'subCatName' : []
}
catObj.categoryId = catValue.id;
catObj.categoryId = catValue.name;
angular.forEach($scope.subcategoryList, function(subValue, subKey) {
if(subValue.category_id == catValue.id) {
var subCatObj = {
'subCategoryId' : '',
'subCategoryName' : ''
}
subCatObj.subCategoryId = subValue.category_id;
subCatObj.subCategoryName = catValue.name;
catObj.subCatName.push(subCatObj);
}
});
$scope.catSubCat.push(catObj);
});