【问题标题】:Changing arrays using map in javascript在 javascript 中使用 map 更改数组
【发布时间】:2018-03-14 09:09:04
【问题描述】:

这是我的 json 对象:

{
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "categoryservices": [
       {
           "category": {
               "id": 1,
               "name": "laptop"
           }
       },
       {
           "category": {
               "id": 2,
               "name": "software"
           }
       }
   ]
}

我想要这样的输出:

{
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "cats": [1,2] // this 1 and 2 is coming from categoriesservices array inside the category object i have id
}

如何使用地图功能做到这一点?我是javascript新手,哪个是好的方法图或forloop?

【问题讨论】:

标签: javascript arrays json object


【解决方案1】:

有关详细信息,请参阅 destructuring assignmentArray.prototype.map()JSON

// Input.
const input = {
  "id": 2,
  "service": "mobile",
  "min": "20",
  "per": "10",
  "tax": "1",
  "categoryservices": [
    {
      "category": {
        "id": 1,
        "name": "laptop"
      }
    },
    {
      "category": {
         "id": 2,
         "name": "software"
      }
    }
  ]
}

// Categories => Objects to Cats => Ids.
const output = (input) => JSON.parse(JSON.stringify({
  ...input,
  cats: input.categoryservices.map(({category: {id}}) => id),
  categoryservices: undefined
}))

// Log.
console.log(output(input))

【讨论】:

    【解决方案2】:

    如果你不担心原始对象的不变性,那么试试这个

    obj['cats'] = obj['categoryservices'].map(cat => cat.category.id);
    delete obj['categoryservices'];
    console.log(obj);
    

    【讨论】:

      【解决方案3】:

      我只是在 categoryservices 数组上使用 .map():

          var output = {
         "id": 2,
         "service": "mobile",
         "min": "20",
         "per": "10",
         "tax": "1",
         "categoryservices": [
             {
                 "category": {
                     "id": 1,
                     "name": "laptop"
                 }
             },
             {
                 "category": {
                     "id": 2,
                     "name": "software"
                 }
             }
           ]
          };
      
          output.cats = output.categoryservices.map((element) => 
          element.category.id);
          delete output.categoryservices;
          console.log(JSON.stringify(output));
      

      【讨论】:

        【解决方案4】:

        使用.map(),它以数组的形式返回值!您要更改的只是categoryservices 键!所以 delete 在你得到想要的价值之后..

        var output = {
           "id": 2,
           "service": "mobile",
           "min": "20",
           "per": "10",
           "tax": "1",
           "categoryservices": [
               {
                   "category": {
                       "id": 1,
                       "name": "laptop"
                   }
               },
               {
                   "category": {
                       "id": 2,
                       "name": "software"
                   }
               }
           ]
        };
        output.cats = output.categoryservices.map(i => i.category.id );
        delete output.categoryservices;
        console.log(output);

        【讨论】:

        • 我在服务器端的 then 函数中使用此代码,因此出现此错误 =>“无法读取未定义的属性 'map'”
        【解决方案5】:

        试试这个工作演示:

        var jsonObj = {
           "id": 2,
           "service": "mobile",
           "min": "20",
           "per": "10",
           "tax": "1",
           "categoryservices": [
               {
                   "category": {
                       "id": 1,
                       "name": "laptop"
                   }
               },
               {
                   "category": {
                       "id": 2,
                       "name": "software"
                   }
               }
           ]
        };
        
        var arr = jsonObj.categoryservices.map(item => item.category.id)
        
        jsonObj.cats = arr;
        delete jsonObj.categoryservices;
        
        console.log(jsonObj);

        【讨论】:

          【解决方案6】:

          试试这个

          var testData={
              "id": 2,
              "service": "mobile",
              "min": "20",
              "per": "10",
              "tax": "1",
              "categoryservices": [
                  {
                      "category": {
                          "id": 1,
                          "name": "laptop"
                      }
                  },
                  {
                      "category": {
                          "id": 2,
                          "name": "software"
                      }
                  }
              ]
          }
          
          testData.cats=[];
          
          testData.categoryservices.forEach(function (item) {
          
              testData.cats.push(item.category.id);
          });
          
          delete testData.categoryservices;
          console.log(testData);
          

          【讨论】:

            【解决方案7】:

            您可以尝试使用每个 jquery:

                <div id="log"></div>
                    var conversation = {
                  'John': {
                    1: 'Test message 1',
                    2: 'Test message 2',
                    'Reply': {
                      3: 'Test message 3',
                      4: 'Test message 4'
                    }
                  },
                  'Jack': {
                    5: 'Test message 5',
                    6: 'Test message 6'
                  }
                };
            
                function iterate(obj) {
                  if (typeof obj === 'string') {
                    $('#log').append((obj + '<br/>'));
                  }
                  if (typeof obj === 'object') {
                    $.each(obj, function(key, value) {
                      iterate(value);
                    });
                  }
                }
            
            iterate(conversation);
            

            【讨论】:

            • 您的回答与 OP 的问题有何关系?
            猜你喜欢
            • 1970-01-01
            • 2017-02-16
            • 1970-01-01
            • 1970-01-01
            • 2021-03-07
            • 2021-09-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多