0

Maybe a stupid question, but I can't do this. So:

I have something like this:

obj = {to:this.to,all:[]};

all:[{},{},{},...] but this is not important

If I do JSON.stringify(obj.all) it returns only this [] without all .

How to achive this { all: [] } ?

2
  • 3
    JSON.stringify({ all: obj.all })? Commented Jun 5, 2018 at 13:13
  • Is not a way to use Object to assign this {} ? Commented Jun 5, 2018 at 13:16

3 Answers 3

1

Are you looking for something like this -

let obj = {to:this.to,all:[]};
let objNew = Object.assign({}, {all: obj.all});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes something like this, but the 2nd parameter something like obj.all
Ok this is the way
1

You can achieve by using one of these

let newObj = { all: JSON.stringify(obj.all) };
console.log(newObj);

let newObjJsonString= JSON.stringify({ all: obj.all });
console.log(newObjJsonString);

Comments

0

You delete all other object and return your object with its key.

   function getWantedObjectWithKey(obj, key){
     var temp = Object.assign({}, obj); 
     Object.keys(temp).forEach(function(value, index){
        if(key != value){
            delete temp[key];
        }
     });
     console.log(JSON.stringify(temp));
     return JSON.stringify(temp);
   }

usage:

getWantedObjectWithKey(obj, 'all');

Comments

Your Answer

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