Reputation: 2021
I have data like,
data = [cluster1:skill1, cluster1:skill2, cluster1:skill3, cluster2, cluster3:skill4, cluster4:skill5];
From the above lookup I am modeling data like below structure using the code I tried,
modelData
[0]:
Main: cluster1
Sub: skill1,skill2,skill3
[1]:
Main: cluster2
Sub: //want this to be empty but now it is undefined
[2]:
Main: cluster3
sub: skill4,skill5
// code JS
dataMap = data().reduce(function (map, item) {
var key = item.split(':')[0];
map[key] = map[key] || [];
map[key].push(item.split(':')[1]);
return map;
}, {});
modelData(Object.keys(dataMap).map(function(key) {
return {
Main: ko.observable(key),
Sub: ko.observableArray(dataMap[key])
};
}));
All I want is if an lookup entry doesnot contains : (colon), then that entry should be considered as Main value and sub array should be empty rather than undefined. I am confused that how can I check that sub array is undefined or defined.
Any suggestion would be helpful
Upvotes: 2
Views: 60
Reputation: 18987
I am confused that how can I check that sub array is undefined or defined.
Looking at your code All you need is to replace this line
map[key].push(item.split(':')[1]); // your element at [1] might be undefined
With
map[key].push(item.split(':')[1] || []); // if [1] is undefined push [] empty array
You need to check if the data you are trying to push is undefined or not. You can do that by using ||
operator.
Upvotes: 1