有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

操纵对象的javascript

我有一个物体看起来像这样

{
   "A": [ "1", "2", "3" ]
}  

我想操纵对象以获得以下结果:

{
    "A": [{
        "A": "1"
    }, {
        "A": "2"
    }, {
        "A": "3"
   }]
}

实现这一目标的途径是什么


共 (2) 个答案

  1. # 1 楼答案

    如果你想知道如何转换

    var myObj = {
       "A": [ "1", "2", "3" ]
    } // this is the object you want to convert
    
    var newObj = {}; //create a new empty object
    
    newObj.A = [];// set a Key "A" of newObj to an empty Array.
    
    for (i = 0; i < myObj.A.length; i++) //loop through the initial object and convert it
        {
    
         newobj.A[i] = {"A":myObj.A[i]} //for every iteration, add an object to the empty array.(newObj.A)
    };
    
  2. # 2 楼答案

    正如@MelanciaUK所提到的,您必须编写代码。你需要调用的不仅仅是convert方法

    以下示例适用于您的用例

    var myObj = {
       "A": [ "1", "2", "3" ]
    }
    
    //convert it
    myObj = {
        "A": [{
            "A": "1"
        }, {
            "A": "2"
        }, {
            "A": "3"
       }]
    }
    
    //print result
    console.log(myObj);