应该将对象列表存储为属性的js对象

时间:2016-11-22 10:20:56

标签: javascript

如果我有一个对象myObj

我希望该对象具有属性客户端,该客户端将包含具有Id和Name属性

的clientObjects列表
var client= { Id: ", Name: "};
var myObj= {
       clients: ????     
}

如何填充客户端属性并在myObj.clients中使用它

3 个答案:

答案 0 :(得分:0)

可能这就是你想要的

var myObj = {}; // Your 'myObj' object

// 'clients' property which will hold list of clientObjects
myObj.clients = [{
  id: "1",
  Name: "name1",
}, {
  id: "2",
  Name: "name2"
}];

console.log(myObj);

答案 1 :(得分:0)

请查看以下内容:



//Following is Array of Client (aka object). Thats all you need
var clientList = [
  { Id: "id1", Name: "Name1"},
  { Id: "id2", Name: "Name2"},
  { Id: "id3", Name: "Name3"},
  { Id: "id4", Name: "Name4"},
  { Id: "id5", Name: "Name5"}
];

//and you can iterate through it in many ways, like this:
clientList.forEach(function(client) {
  console.log(`Client Id:${client.Id} Name:${client.Name}`);
})




答案 2 :(得分:0)

可能这会对你有帮助.....

var myObject = {clients:[]};
myObject.clients.push({id:"1",name:"name"});
myObject.clients.push({id:"2",name:"name"});
console.log(myObject);