2

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

2
  • please add some real data. please have a look here: minimal reproducible example Commented Dec 22, 2016 at 9:04
  • Can you format you data to reflect actual content in it.. at the moment its not even valid data.. Commented Dec 22, 2016 at 9:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is really awesome! I tried, It is adding empty value with array length 1. I dont even want this empty value pushed array. I just want this array to be empty with length 0. Is there any way to do this.
@MJSuriya replace "" with [] .. Let me know if that is what you are looking for
That's amazing ! Thanks a lot
@MJSuriya glad to help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.