Reputation: 65
For privacy reasons I will explain my problem using a simple example. I want to add information about an employee into the Object with this format:
const infoList = {
"01": {
"name": "alex",
"family": "tirko",
"address": {
"city": "berlin",
"street": "tomas",
}
},
"02": {
"name": "sara",
"family": "johansson",
"address": {
"city": "denmark",
"street": "vigerslev",
}
},
}
My question is how to add objects "03" and "04", with the above format in code using function?
What I mean by that is I want to create "03" and "04" and so on with the same format and want to get all of its elements from input.
User must enter complete data to store it in the object.
Any solution would be my appreciated
Upvotes: 0
Views: 186
Reputation: 3691
This is one possible way to achieve the desired objective.
Code Snippet
const addBtn = document.getElementById("btnAdd"); // manipulate the "add" button
const resDiv = document.getElementById("res"); // manipulate the "res" div
const dataObject = {}; // the main object to hold all user-input data
// direct access to the 4 inputs namely: name, family, city, street
const inpList = "name, family, city, street"
.split(", ")
.map(name => ({
name,
elt: document.getElementById(name)
}));
// set-up a default value for each input
inpList.forEach(
({ name, elt }, i) => elt.value = `${name}-${Object.keys(dataObject).length + 1}`
);
// method to enable or disable "add" button based on input values
const enableAddBtn = () => {
addBtn.disabled = (
inpList.every(({ elt }) => elt.value.length > 0)
? ""
: "disabled"
)
};
// add "change" event-listener to each input (ie, name, family, city, street)
inpList.forEach(({ elt }) => {
elt.addEventListener("change", (ev) => {
if (elt.value.length > 0) enableAddBtn();
else addBtn.disabled = "disabled"
});
return () => elt.removeEventListener("change");
});
// to render the "dataObject" to the UI
const rerenderData = () => {
const rowsHTML = Object.entries(dataObject)
.map( // consolidate all the existing data rows
(
[k, {name, family, address: { city, street}}]
) => (
`<tr>
<td>${k}</td><td>${name}</td><td>${family}</td>
<td>${city}</td><td>${street}</td>
</tr>`
)
).join('');
// repopulate the "res" div inner-html
resDiv.innerHTML = `
<table>
<thead>
<tr>
<td>ID</td><td>Name</td><td>Family</td>
<td>City</td><td>Street</td>
</tr>
</thead>
<tbody>
${rowsHTML}
</tbody>
</table>
`;
};
// add "click" event listener to "add" button
addBtn.addEventListener("click", () => {
// extract the input values for quick, direct access
const [
name, family, city, street
] = inpList.map(
({ elt }) => elt.value
);
// construct the desired "sub-object"
const myObject = {
name, family, address: { city, street }
};
// add the "sub-object" to the main "dataObject"
// the "01", "02", "03", ... keys are created using ".padStart()"
dataObject[
(
Object.keys(dataObject).length + 1
).toString()
.padStart(2, 0)
] = myObject;
// now, re-render the data
rerenderData();
// additional console.log to show data as JSON
console.log('data stored in object: ', JSON.stringify(dataObject));
});
.outer {
border: 2px solid black;
width: 45%;
padding: 10px;
}
.btnContainer {
display: flex;
justify-content: space-around;
}
.inputBoxes {
padding: 15px;
}
.inputBox {
margin: 10px;
display: flex;
justify-content: space-between;
}
td { padding: 5px; }
tr { border-bottom: 1px solid grey; }
.as-console-wrapper { max-height: 100% !important; top: 75%; }
<div class="outer">
<div class="inpBoxes">
<div class="inputBox">
<label for="name">Name</label>
<input id="name">
</div>
<div class="inputBox">
<label for="family">Family</label>
<input id="family">
</div>
<div class="inputBox">
<label for="city">City</label>
<input id="city">
</div>
<div class="inputBox">
<label for="street">Street</label>
<input id="street">
</div>
</div>
<div class="btnContainer">
<button id="btnAdd">Add</buttun>
</div>
<hr />
<div id="res">
</div>
</div>
Please use FULL PAGE
to view demo
Explanation
Inline comments describe the significant aspects of the code in the above snippet.
Upvotes: 0
Reputation: 889
You can try this:
const infoList = {
"01": {
"name": "alex",
"family": "tirko",
"address": {
"city": "berlin",
"street": "tomas",
}
},
"02": {
"name": "sara",
"family": "johansson",
"address": {
"city": "denmark",
"street": "vigerslev",
}
},
}
const addInfo = (info) => {
if (!info["name"] || !info["family"] || !info["address"] || !info["address"]["city"] || !info["address"]["street"]) {
throw 'Object is not structured properly';
} else {
const len = Object.keys(infoList).length + 1;
const newEl = len > 9? `${len}`: `0${len}`;
infoList[newEl] = {
"name": info["name"],
"family": info["family"],
"address": {
"city": info["address"]["city"],
"street": info["address"]["street"]
}
}
}
}
Upvotes: 1