在javascript中使用map返回新数组

时间:2018-03-14 13:26:37

标签: javascript arrays object

我正在req.body中构建一个nodejs应用程序:

我有这个对象:

{
   "id": 8,
   "username": "sameer",
   "age": "20"
   "details": [
       {
           "category": {
               "id": 1,
               "nickname": "sam"
           }
       },
       {
           "category": {
               "id": 2,
               "nickname": "basha"
           }
       }
   ]
}

我的预期输出:

 {
   "id": 8,
   "username": "sameer",
   "age" : "20",
   "final": [1,2]  // this id coming from category id.
  }

我尝试了这种静态方式:

var data = 'myJsonStuffs'

var result = data.details.map(x => {
   return({
     "id": data.id,
     "username": data.username,
     "age": data.age,
     "final": [1,2] // i want this dynamic
   });
});

console.log(result);

如何使用地图做到这一点?这是否可以返回动态值。

3 个答案:

答案 0 :(得分:2)

您可以使用map

功能

重要提示:此方法会改变原始对象。

var obj = {   "id": 8,   "username": "sameer",   "age": "20",   "details": [       {           "category": {               "id": 1,               "nickname": "sam"           }       },       {           "category": {               "id": 2,               "nickname": "basha"           }       }   ]};

obj.final = obj.details.map((d) => d.category.id);
delete obj.details

console.log(obj)
.as-console-wrapper { max-height: 100% !important; top: 0; }

保持原始的obj结构

var obj = {   "id": 8,   "username": "sameer",   "age": "20",   "details": [       {           "category": {               "id": 1,               "nickname": "sam"           }       },       {           "category": {               "id": 2,               "nickname": "basha"           }       }   ]};

var newObj = Object.assign({}, { 
                id: obj.id, 
                username: obj.username, 
                age: obj.age, 
                final: obj.details.map((d) => d.category.id)
             });

console.log(newObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

我就是这样做的。

我希望这会有所帮助



const data = {
  id: 8,
  username: "sameer",
  age: "20",
  details: [
   {
     category: {
       id: 1,
       nickname: "sam"
     }
   },
   {
     category: {
       id: 2,
       nickname: "basha"
     }
   }
  ]
};

const result = Object.assign(
  {}, // Empty object to avoid mutating 'data'
  data,
  { details: data.details.map(detail => detail.category.id) } // Override 'details'
);

console.log(result);




答案 2 :(得分:-1)

也许你想要这个? 你可以使用' i'作为索引并使用

填充数组
var data = 'myJsonStuffs'

var result = data.details.map((x,i) => {
   return({
     "id": data.id,
     "username": data.username,
     "age": data.age,
     "final": [i] // i want this dynamic
   });
});

console.log(result);