【问题标题】:What is the best way to create a JSON or Object into another Object in Javascript?在 Javascript 中将 JSON 或对象创建为另一个对象的最佳方法是什么?
【发布时间】:2018-10-03 14:09:45
【问题描述】:

我正在使用 ajax 从数据库中获取结果,如下面的代码:

success: function (dados) {
            $.each(dados, function () {
                $.each(this, function (index, value) { ... });
            });
        }

我从数据库中得到的回报应该是这样的:

[{_id: "001",
name: "John",
age: 38},

{_id: "002",
name: "Marie",
age: 27}]

我想要一个这样的对象:

Object[_id] = {name: ..., age: ...}

因此,对于每个 _id,我都会有一个名称和年龄,以便使用 Javascript 进行迭代和处理。 我怎么能这样做?

【问题讨论】:

    标签: json ajax object


    【解决方案1】:

    你可以使用reduce:

    let formattedObj = dados.reduce((obj, item) => {
        obj[item._id] = {
            name: item.name, 
            age: item.age
        }
    
        return obj;
    }, {});
    

    【讨论】:

      猜你喜欢
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多