angularjs基于id从现有数组创建新的json数组,因为关键的剩余对象是值

时间:2017-04-28 05:25:36

标签: angularjs json

我有bookingData.roomList,

{ "address": "x@gmail.com" }
{ "address": "xy@gmail.com" }

我想创建一个像roomListData

这样的新值
bookingData.roomList = [{id : <>, roomCategory : Single, number : 2}, {id:<>,roomCategory : Double, number : 1}]
请某人帮我解决这个问题

4 个答案:

答案 0 :(得分:1)

`

&#13;
&#13;
var roomList = [{id : 1, roomCategory : "Single", number : 2}, {id:2,roomCategory : "Double", number : 1}];
var roomListData = {};
for(var i=0;i< roomList.length ;++i){
    var temp =  roomList[i];
    var id = temp.id;
    delete temp.id;
    roomListData[id]=temp;
}
console.log(roomListData);
&#13;
&#13;
&#13; `

答案 1 :(得分:1)

我认为这就是你所需要的。要将属性值用作属性标签,请使用[]

var roomList = [{id: 4514,roomCategory: "Single", number: 2}, 
                {id: 4542,roomCategory: "Double", number: 1}];

var newJson = [];
roomList.forEach(function(item) {
  newJson.push({
  [item.id] :{
        "roomCategory": item.roomCategory,
        "number": item.number
        }
  });
});
console.log(newJson);

答案 2 :(得分:1)

<强> 1。使用JavaScript for...in循环:

var bookingData = {
	"roomList": [{
		id: 1,
		roomCategory: "Single",
		number: 2
	}, {
		id: 2,
		roomCategory: "Double",
		number: 1
	}]
};

var roomListData = {};

for(var i in bookingData.roomList) {
  roomListData[bookingData.roomList[i].id] = {
    "roomCategory" : bookingData.roomList[i].roomCategory,
    "number" : bookingData.roomList[i].number
  }
}

console.log(roomListData);

<强> 2。使用Array.map()方法和ES6 Arrow函数:

var bookingData = {
	"roomList": [{
		id: 1,
		roomCategory: "Single",
		number: 2
	}, {
		id: 2,
		roomCategory: "Double",
		number: 1
	}]
};

var roomListData = {};

bookingData.roomList.map(item =>
  roomListData[item.id] = {
    "roomCategory" : item.roomCategory,
    "number" : item.number
  });

console.log(roomListData);

第3。使用ES6点差分配:

var bookingData = {
	"roomList": [{
		id: 1,
		roomCategory: "Single",
		number: 2
	}, {
		id: 2,
		roomCategory: "Double",
		number: 1
	}]
};

function createObj(a,b) {
  var roomListData = {};
  roomListData[a.id] = a,delete a.id;
  roomListData[b.id] = b,delete b.id;
  return roomListData;
}

var res = createObj(...bookingData.roomList);
console.log(res);

答案 3 :(得分:0)

我假设uuid1你的意思是一个新的uuid,而不是&uuid&#39;附加数字1。

bookingData.roomList = [{id : <>, roomCategory : Single, number : 2}, {id:<>,roomCategory : Double, number : 1}]

roomList = {};
bookingData.forEach(function(element, index, array) {
    var uuid = GenerateNewUUID();
    // or uuid = element.id;
    delete element.id;
    roomList[uuid] = element;
});