0

I need some observable for my JSON. Data looks like this:

{
"event": [{
    "id": 1,
    "name": "First",
    "param": {
        "a": 1,
        "b": [1, 2, 3]
    }
}, {
    "id": 2,
    "name": "Second",
    "param": {
        "a": 1,
        "b": [1, 2, 3, 4, 5, 6, 7],
        "c": 3
    }
}]

}

How to get param like object? I don't know - how many k=>v or object inside param. I need to know - param has change, and I'd like to get data.attr('event.1.param') and got

"param": {
    "a": 1,
    "b": [1, 2, 3, 4, 5, 6, 7],
    "c": 3
}

Is it possible? Or may be you can tell me about easier way?

ramblinjan
  • 6,578
  • 3
  • 30
  • 38
Vladislav
  • 371
  • 4
  • 12

2 Answers2

1

There are many ways to get the actual object bus basically you can treat them like any array:

var o = new can.Observe({
    "event": [{
        "id": 1,
        "name": "First",
        "param": {
            "a": 1,
            "b": [1, 2, 3]
        }
    }, {
        "id": 2,
        "name": "Second",
        "param": {
            "a": 1,
            "b": [1, 2, 3, 4, 5, 6, 7],
            "c": 3
        }
    }]
});

o.attr('event.0.param') // -> { "a": 1, "b": [1, 2, 3] }
// Get param 1
var index = 1;
o.attr('event.' + index + '.param');

// Got through all events
o.attr('event').forEach(function(data) {

});

// You can also handle it like a normal array
var index = 1;
o.event[index].attr('param')
Daff
  • 43,734
  • 9
  • 106
  • 120
  • You have a mistake. In this case: o.attr('event.0.param'); We have something other, than simple object: {"_data":{"a":1,"b":{"0":1,"1":2,"2":3,"length":3,"_cid":".observe6","jQuery18203471092500258237":{"events":{"change":..... We need to use o.attr('event.0.param').attr(); And we'll get { "a": 1, "b": [1, 2, 3] } – Vladislav Dec 10 '12 at 07:28
0

Sorry pals, we just need to add .attr() at the end...

o.attr('event.0.param').attr()

In this case we will have { "a": 1, "b": [1, 2, 3] }

Vladislav
  • 371
  • 4
  • 12