代码之家  ›  专栏  ›  技术社区  ›  Cristian

转换json中的对象数组元素

  •  0
  • Cristian  · 技术社区  · 6 年前

    也许是个愚蠢的问题,但我做不到。所以:

    我有这样的东西:

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

    all:[{},{},{},...] 但这并不重要

    如果我这样做 JSON.stringify(obj.all) 它只返回这个 [] 没有 all .

    如何做到这一点 { all: [] } ?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Pardeep Jain    6 年前

    你在找这样的东西吗-

    let obj = {to:this.to,all:[]};
    let objNew = Object.assign({}, {all: obj.all});
    
        2
  •  2
  •   ihist    6 年前

    你可以通过使用其中一个

    let newObj = { all: JSON.stringify(obj.all) };
    console.log(newObj);
    
    let newObjJsonString= JSON.stringify({ all: obj.all });
    console.log(newObjJsonString);
    
        3
  •  1
  •   Berk Akkerman    6 年前

    删除所有其他对象并返回对象及其键。

       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);
       }
    

    用途:

    getWantedObjectWithKey(obj, 'all');