1

I have a object like this.

var Obj = {
    obj1 : {
        val : 1,
        id : 1
    }
    obj2 : {
        val : 2,
        id :2
    }
    obj3 : {
        val : 3,
        id :3
    }
}

I want my obj1and all sub object into one array so I can retrieve the value. I want array in array because I want to retrieve them, Since it is dynamic I can not use Obj.obj1 therefore I want to push into array.

Can Anybody tell How Can I get that. Thanks for help

1
  • What have you tried? It's also unclear what you want the output to look like. Do you want the output to just be [1, 2, 3]? Commented Jan 19, 2017 at 5:37

1 Answer 1

2

Use Object.keys and Array#map methods to convert it to an array but the order is not guaranteed since object properties don't have any order.

var Obj = {
  obj1: {
    val: 1,
    id: 1
  },
  obj2: {
    val: 2,
    id: 2
  },
  obj3: {
    val: 3,
    id: 3
  }
};

var res = Object.keys(Obj).map(function(k) {
    return Obj[k];
  })

console.log(res);

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

8 Comments

Object.values(Obj) is another option (though browser support is lower)
@4castle : It's not widely supported
@4castle That works fine, But any suggestion how to delete this record from the object. eg : if(arr[I].val = 1) then I want to delete Obj1 mean respective object from the main object.
@David : use delete keyword
Thanks a ton. Work like a charm.
|

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.