【问题标题】:How to add name and convert array values to JSON?如何添加名称并将数组值转换为 JSON?
【发布时间】:2016-03-17 22:56:12
【问题描述】:

我有一个数组,像这样:

["1", "hello1@example.com", "user111", "something1"],
["2", "hello2@example.com", "user222", "something2"],
["3", "hello3@example.com", "user333", "something3"],
...
["N", "helloN@example.com", "userNNN", "somethingN"]

我怎样才能把它变成这样的 JSON:

{ 
  "order" : "1" 
, "email": "hello1@example.com" 
, "username": "user111" 
, "note": "something1" 
},
{ 
  "order" : "2"
, "email": "hello2@example.com"
, "username": "user222" 
, "note": "something2"
},
{ 
  "order" : "3" 
, "email": "hello3@example.com" 
, "username": "user333" 
, "note": "something3" 
}, 

... 

{ 
  "order" : "N" 
, "email": "helloN@example.com" 
, "username": "userNNN" 
, "note": "somethingN" 
}

我是自学 JavaScript,如果您能推荐一个类似的案例或文档以了解更多信息,我将不胜感激。

谢谢。

【问题讨论】:

  • 我正在考虑通过内部数组运行一个for循环,取出第一项“1”并将“order”:“1”放回去,取出第二项“hello1@example .com”并放回“email”:“hello1@example.com”等等,直到我有一个正确的“name:value”配对数组,然后使用 json.stringify() 该数组。这是好方法吗?

标签: javascript arrays json


【解决方案1】:

您可以通过多种方式做到这一点,例如使用经典的 for 循环。

我目前喜欢的方式是使用 Array.map:

array = [
    ["1", "hello1@example.com", "user111", "something1"],
    ["2", "hello2@example.com", "user222", "something2"],
    ["3", "hello3@example.com", "user333", "something3"],
    ...
    ["N", "helloN@example.com", "userNNN", "somethingN"]
];

var arr2 = array.map(function(el, i) {
    return {
        order: el[0],
        email: el[1],
        username: el[2],
        note: el[3]
    };
});

请参阅here 以获取参考。里面有很多好东西。

【讨论】:

    【解决方案2】:

    类似这样的:

    var arrayOfObjs = [];
    for(var i in inputArray) {
        var data = inputArray[i];
        var obj = {
            order: data[0],
            email: data[1],
            username: data[2],
            note: data[3]
        };
        arrayOfObjs.push(obj);
    }
    
    console.log(arrayOfObjs);
    

    您首先遍历数组,因为您知道内部数组的长度始终为 4 且 [0 = order, 1 = email, 2 = username, 3 = note],您可以安全地创建新对象并添加它们到一个新数组。您也可以在数组中执行此操作,这意味着您的输入数组会更新为新格式(您基本上不会创建新数组):

    inputArray[i] = obj; // replace line `arrayOfObjs.push(obj)` with this one
    

    【讨论】:

    • 非常感谢。替换和更新 inputArray 对我来说更容易理解和使用。所以我接受了你的回答。祝你有美好的一天!
    【解决方案3】:

    在纯 javaScript 中,我会选择 Chiesa 的解决方案。如果你想使用一个库,这里有一种使用 underscore.js 的方法:

    var new_array = _.map(array, function(entry) {
       return _.object(['order', 'email', 'username', 'note'], entry);
    });
    
    var json = JSON.stringify(new_array);
    

    【讨论】:

    • 是的,我同意 Chiesa 的代码很短,但是当我能更好地理解 JavaScript 时,我会使用这种方式。谢谢你的建议。
    猜你喜欢
    • 2019-10-22
    • 2021-04-30
    • 2021-11-26
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多