Reputation: 61
how to store arrays of data in an Object. I tried to store data using
var namelist = [], labelDetails = {};
addedLabels_list.push(name);
labedDetails_list[ownerName] = Address;
namelist holds unique names while labelDetails store data in key value pair
Namelist :
0:"ahmad"
1:"jhon"
2: "hamza"
3: "emma"
labelDetails :
ahmad :"lahore"
jhon :"USA"
hamza :"UK"
emma :"USA, Calforina"
But when same owner name has multiple addresses it won't work.
Let's say Emma
live in USA, California
and her second address is Washington Dc
and it replaces emma :"washington dc"
var namelist = [], labelDetails = {};
addedLabels_list.push(name);
labedDetails_list[ownerName] = Address;
Upvotes: 0
Views: 270
Reputation: 13356
I would try designing a data structure that also stays stable over time, thus choosing a name based (better id based) key-value person-registry that for each person refers a single data item. This data node then is the root for all person related data that yet will come and then has to be taken care of as well ...
var personRegistry = {
ahmad: {
addressList: ["Lahore"]
},
jhon: {
addressList: ["USA"]
},
hamza: {
addressList: ["UK"]
},
emma: {
addressList: ["USA, California"]
}
}
function storeAddress(name, address) {
var store = personRegistry[name];
if (!store) {
store = personRegistry[name] = {};
store.addressList = [];
}
// prevent address duplicates ...
//if (!store.addressList.includes(address)) { // use that if available.
if (store.addressList.indexOf(address) < 0) {
store.addressList.push(address);
}
}
console.log('personRegistry : ', personRegistry);
storeAddress("emma", 'USA, California');
storeAddress("emma", 'USA, Washington DC');
storeAddress("emma", 'USA, Washington DC');
storeAddress("susan", 'Canada, Toronto');
storeAddress("susan", 'Canada, Toronto');
console.log('personRegistry : ', personRegistry);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Upvotes: 1
Reputation: 2258
You definitely have to make some changes to make your solution work, I would suggest,
labelDetails = {
"ahmad" : ["lahore"],
"jhon" : ["USA"],
"hamza" : ["UK"],
"emma" : ["USA, Calforina"]
};
labelDetails[ownerName].push("washington dc");
Upvotes: 1
Reputation: 2209
For arrays, the key should be unique, so in this case, you can use array to store multiple address for a the same key, this is a start :
function myFunction(){
var namelist = ["ahmad", "jhon", "hamza", "emma"],
labelDetails = {ahmad :["lahore"], jhon :["USA"], hamza :["UK"], emma :["USA, Calforina"]};
labelDetails["emma"].push("washington dc");
console.log(labelDetails);
}
<button onclick="javascript:myFunction()">Click me</button>
Upvotes: 1