how to add specific links to search keywords - javascript

This is a search code i am working on but I want to give specific links to the members of the array 'people' so that 'rock' would have its own link to another page, 'brock', would have its own link and so on, the search is working perfectly but a i want the result to link to other pages
here is the code(without html)
const people = [
{name: 'david'},
{name: 'patel'},
{name: 'kevin'},
{name: 'coco'},
{name: 'brock'},
{name: 'rock'}
];
const list = document.getElementById('list');
//function to set the list
function setList(group){
clearlist();
for(const person of group)
{
const item = document.createElement('a');
item.classList.add('list-group-item');
const text =document.createTextNode(person.name);
item.appendChild(text);
list.appendChild(item);
}
if(group.lenght==0){
setnoresult();
}
}
function clearlist(){
while(list.firstChild)
{
list.removeChild(list.firstChild);
}
}
function setnoresult(){
const item = document.createElement('li');
item.classList.add('list-group-item');
const text =document.createTextNode('no result found');
item.appendChild(text);
list.appendChild(item);
}
function getrelevancy(value, searchterm){
if(value === searchterm)
{
return 2;
}
else if(value.startsWith(searchterm))
{
return 1;
}
else if(value.includes(searchterm))
{
return 0;
}
else{
return -1;
}
}
const searchinput = document.getElementById('search');
searchinput.addEventListener('input',(event) => {
let value = event.target.value;
if(value && value.trim().length >0)
{
value = value.trim().toLowerCase();
setList(people.filter(person => {
return person.name.includes(value);
}).sort((personA, personB) =>{
return getrelevancy(personB.name, value- getrelevancy(personA.name ,value))
}));
}
else{
clearlist();
}
// console.log(event.target.value);
})

You could something like a link: 'page.com to your object then add the link the <a> by doing item.href = people[index].link. Hard to explain, let me just show an example:
const people = [ {name: "Jeff", link: "page.com/jeff"}, {name: "Jo", link: "page.com/Jo"} ];
And then call setList like this:
setList(people.filter(person => { return people.indexOf(person.name) }));
or something like that. Then set the href and name by:
const text = document.createTextNode(people[group].name);
item.href = people[group].link;
I really hope you understand what I just said.

Related

javascript quiz how to give the answer array a default value?

I'm creating a quiz that requires every answer to be answered. The problem is that you should be able to skip questions if you don't have an answer. I'm trying to set a default answer everytime I press next so when I try to skip one I don't have to answer for it to have a value. The default value I want is each time the last value of my array.
next and previous question
SetQuestion(question) {
if (this.questionNumber >= 0) {
let oldAnswerButton = document.querySelectorAll('.filter_anwser');
// Deletes old question when the next question is clicked
for (let answerButton of oldAnswerButton) {
answerButton.style.display = 'none';
}
}
this.questionNumber = question;
let q = this.quiz[question];
// Check if your at the last question so the next button will stop being displayed.
if (this.questionNumber === Quiz.length - 1) {
this.nextbtn.style.display = 'none';
this.prevbtn.style.display = 'block';
this.resultbtn.style.display = 'grid';
} else if (this.questionNumber === 0) {
this.nextbtn.style.display = 'block';
this.prevbtn.style.display = 'none';
this.resultbtn.style.display = 'none';
} else {
this.nextbtn.style.display = 'block';
this.prevbtn.style.display = 'block';
this.resultbtn.style.display = 'none';
}
// Displays Question
this.questionName.textContent = q.questionText;
this.questionName.id = "questionID";
return q;
console.log(this.getLink())
console.log(this.tmp)
}
IntoArray() {
const UrlVar = new URLSearchParams(this.getLink())
this.UrlArray = [...UrlVar.entries()].map(([key, values]) => (
{[key]: values.split(",")}
)
);
}
NextQuestion() {
// let quizUrl = this.url[this.questionNumber];
let question = this.SetQuestion(this.questionNumber + 1);
let pre = question.prefix;
let prefixEqual = pre.replace('=', '');
let UrlArr = this.UrlArray;
let UrlKeys = UrlArr.flatMap(Object.keys)
let answers = question.chosenAnswer.slice(0, -1);
this.clicked = true;
// Displays answers of the questions
for (let y = 0; y < answers.length; y++) {
let item = answers[y];
// Display answer buttons
if (UrlKeys.includes(prefixEqual)) {
console.log("exists");
let btn = document.querySelector('button[value="' + item.id + '"]');
btn.style.display = 'block';
} else {
let btn = document.createElement('button');
btn.value = item.id;
btn.classList.add("filter_anwser", pre)
btn.id = 'answerbtn';
btn.textContent = item.name;
this.button.appendChild(btn);
}
// let quizUrl = control.url[control.questionNumber];
// // console.log(this.tmp);
// if (quizUrl === undefined) {
// quizUrl.push(question.prefix[y] + '');
// }
// if (quizUrl === undefined){
// this.tmp.push('');
// }
}
this.IntoArray();
}
PrevQuestion() {
let question = this.SetQuestion(this.questionNumber - 1);
let answers = question.chosenAnswer.slice(0, -1);
// Displays answers of the questions
for (let y = 0; y < answers.length; y++) {
let item = answers[y];
// Display answer buttons
let btn = document.querySelector('button[value="' + item.id + '"]');
btn.style.display = 'block';
}
this.IntoArray();
}
Link creator:
/**
* Returns the parameters for the URL.
*
* #returns {string}
*/
getLink() {
this.tmp = [];
for (let i = 0; i < this.url.length; i++) {
// Check if question is from the same quiz part and adds a , between chosen answers and add the right prefix at the beginning
if (this.url[i].length > 0) {
this.tmp.push("" + Quiz[i].prefix + this.url[i].join(","))
// console.log(this.url)
}
if (this.url[i].length === 0) {
this.tmp.push("");
}
}
/// If answers are from different quiz parts add a & between answers.
return "" + this.tmp.join("&");
// console.log(this.url[i].prefix);
};
Answer click event
control.button.addEventListener("click", function (e) {
const tgt = e.target;
control.clicked = true;
// clear the url array if there's nothing clicked
if (control.url.length === control.questionNumber) {
control.url.push([]);
}
let quizUrl = control.url[control.questionNumber];
// Check if a button is clicked. Changes color and adds value to the url array.
if (quizUrl.indexOf(tgt.value) === -1) {
quizUrl.push(tgt.value);
e.target.style.backgroundColor = "orange";
// Check if a button is clicked again. If clicked again changes color back and deletes value in the url array.
} else {
quizUrl.splice(quizUrl.indexOf(tgt.value), 1);
e.target.style.backgroundColor = "white";
}
console.log(control.getLink());
console.log(quizUrl)
})
array:
class QuizPart {
constructor(questionText, chosenAnswer, prefix, questionDescription) {
this.questionText = questionText;
this.chosenAnswer = chosenAnswer;
this.prefix = prefix;
this.questionDescription = questionDescription;
}
}
class ChosenAnswer {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
let Quiz = [
new QuizPart('Whats your size?', [
new ChosenAnswer('6595', '41'),
new ChosenAnswer('6598', '42'),
new ChosenAnswer('6601', '43'),
new ChosenAnswer('', ''),
], 'bd_shoe_size_ids=',
'The size of your shoes is very important. If you have the wrong size, they wont fit.'),
new QuizPart('What color would you like?', [
new ChosenAnswer('6053', 'Red'),
new ChosenAnswer('6044', 'Blue'),
new ChosenAnswer('6056', 'Yellow'),
new ChosenAnswer('6048', 'Green'),
new ChosenAnswer('', ''),
], 'color_ids=',
'Color isn t that important, It looks good tho.'),
new QuizPart('What brand would you like?', [
new ChosenAnswer('5805', 'Adidas'),
new ChosenAnswer('5866', 'Nike'),
new ChosenAnswer('5875', 'Puma'),
new ChosenAnswer('', ''),
], 'manufacturer_ids=',
'Brand is less important. Its just your own preference'),
]
I tried giving the array's in link creator and my eventlistener a default value and replacing it when I get and actual value from one of my buttons, but it just doesn't work. Can anybody help me?
I understand, that it might be a bit far from what you expect for an answer - but why don't you have a look at a reactive tool, like Vue? It has all the tools that you might need for such a task, and maybe more:
the whole quiz can be abstracted to a simple array of objects (the questions)
next, prev, set default answer becomes a breeze
easy to extend (with questions)
simple to update (template, features, etc.)
Vue.component('QuizQuestion', {
props: ['data', 'selected'],
computed: {
valSelected: {
get() {
return this.selected
},
set(val) {
this.$emit('update:selected', val)
}
},
},
template: `
<div>
{{ data.text }}<br />
{{ data.description }}<br />
<div class="quiz-options">
<label
v-for="val in data.options"
:key="val[0]"
>
<input
type="radio"
:name="data.text"
:value="val"
v-model="valSelected"
/>
{{ val[1] }}
</label>
</div>
</div>
`
})
new Vue({
el: "#app",
computed: {
currentQuestion() {
return this.questions[this.current]
},
hasPrev() {
return !!this.current
},
hasNext() {
return this.current < this.questions.length - 1
},
},
data() {
return {
current: 0,
questions: [{
text: 'Whats your size?',
description: 'The size of your shoes is very important. If you have the wrong size, they wont fit.',
options: [
['6595', '41'],
['6598', '42'],
['6601', '43'],
['', ''],
],
selected: null,
}, {
text: 'What color would you like?',
description: 'Color isn\'t that important, It looks good tho.',
options: [
['6053', 'Red'],
['6044', 'Blue'],
['6056', 'Yellow'],
['6048', 'Green'],
['', ''],
],
selected: null,
}, {
text: 'What brand would you like?',
description: 'Brand is less important. Its just your own preference',
options: [
['5805', 'Adidas'],
['5866', 'Nike'],
['5875', 'Puma'],
['', ''],
],
selected: null,
}, ],
}
},
methods: {
selectDefault() {
this.questions[this.current] = {
...this.questions[this.current],
selected: this.questions[this.current].options.slice(-1)[0],
}
},
getPrev() {
if (this.hasPrev) {
if (!this.currentQuestion.selected) {
this.selectDefault()
}
this.current -= 1
}
},
getNext() {
if (this.hasNext) {
if (!this.currentQuestion.selected) {
this.selectDefault()
}
this.current += 1
}
},
},
template: `
<div>
<quiz-question
:data="currentQuestion"
:selected.sync="currentQuestion.selected"
/><br />
<button v-if="hasPrev" #click="getPrev">PREV</button>
<button v-if="hasNext" #click="getNext">NEXT</button>
<button v-if="!hasNext">RESULT</button>
</div>
`
})
.quiz-options {
display: flex;
flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
EDIT
But, if frameworks/libraries are not to be used, here's a more OOP approach:
class Quiz {
constructor(questions) {
this._current = 0
this._questions = questions
}
get current() {
return this._current
}
set current(val) {
this._current = val
}
get hasNext() {
return this.current < this.questions.length - 1
}
get hasPrev() {
return !!this.current
}
get questions() {
return this._questions
}
get next() {
this.current = this.hasNext ? this.current + 1 : this.current
return this.currentQuestion
}
get prev() {
this.current = this.hasPrev ? this.current - 1 : this.current
return this.currentQuestion
}
get currentQuestion() {
return this.questions[this.current]
}
}
class Question {
constructor({
text,
description,
options,
prefix,
}) {
this.text = text
this.desc = description
this.prefix = prefix
this._options = options.map(([key, val]) => ({
id: key,
value: [key, val],
selected: false,
}))
}
get options() {
return this._options
}
set options(newOptions) {
this._options = newOptions
}
get selected() {
return this.options.find(({
selected
}) => !!selected)
}
set selected(selectedVal) {
this.options = [...this.options.map(({
value: [key, val],
selected,
...rest
}) => {
return {
...rest,
value: [key, val],
selected: key === selectedVal
}
})]
}
get lastOption() {
return this.options.slice(-1)[0]
}
setDefault() {
if (!this.selected) {
this.selected = this.lastOption.id
}
}
}
const urlParser = (quiz) => {
return quiz.questions.map(({
prefix,
selected = {
value: ['']
}
}) => {
const s = selected.value[0] ? selected.value[0] : ''
return `${prefix}${s}`
}).join('&')
}
const qArr = [{
text: 'text1',
description: 'desc1',
options: [
['1_1', '11'],
['1_2', '12'],
['1_3', '13'],
],
prefix: 'prefix_1_',
},
{
text: 'text2',
description: 'desc2',
options: [
['2_1', '21'],
['2_2', '22'],
['2_3', '23'],
],
prefix: 'prefix_2_',
},
{
text: 'text3',
description: 'desc3',
options: [
['3_1', '31'],
['3_2', '32'],
['3_3', '33'],
],
prefix: 'prefix_3_',
},
]
const getOptionsHtml = ({
text,
options
}) => {
let html = ''
options.forEach(({
id,
value,
selected
}, i) => {
html += `
<label>
<input
class="question-input"
type="radio"
name="${text}"
value="${value[0]}"
${selected ? 'checked' : ''}
/>
${value[1]}
</label>
`
})
return html
}
const getSingleQuestionHtml = (q) => {
const optionsHtml = getOptionsHtml({
text: q.text,
options: q.options
})
return `
${q.text}<br />
${q.desc}<br />
${optionsHtml}
`
}
const registerEventHandlers = ({
container,
question
}) => {
const radioBtns = document.querySelectorAll('.question-input')
radioBtns.forEach((input, i) => {
input.addEventListener('change', function(e) {
question.selected = e.target.value
})
})
}
const updateHtml = ({
container,
question
}) => {
container.innerHTML = getSingleQuestionHtml(question)
registerEventHandlers({
container,
question
})
};
const updateContainer = (container) => (question) => updateHtml({
container,
question
});
const setElDisplay = ({
el,
display
}) => {
if (display) {
el.classList.add("d-inline-block")
el.classList.remove("d-none")
} else {
el.classList.remove("d-inline-block")
el.classList.add("d-none")
}
}
const updateBtnVisibility = ({
btnNext,
btnPrev,
btnResult,
quiz
}) => () => {
setElDisplay({
el: btnNext,
display: quiz.hasNext
})
setElDisplay({
el: btnResult,
display: !quiz.hasNext
})
setElDisplay({
el: btnPrev,
display: quiz.hasPrev
})
}
(function() {
const quiz = new Quiz(qArr.map(q => new Question(q)))
const container = document.getElementById('quiz-container')
updateQuizContainer = updateContainer(container)
updateQuizContainer(quiz.currentQuestion)
const btnPrev = document.getElementById('btn-prev')
const btnNext = document.getElementById('btn-next')
const btnResult = document.getElementById('btn-result')
const updateBtns = updateBtnVisibility({
btnPrev,
btnNext,
btnResult,
quiz
})
updateBtns()
btnPrev.addEventListener('click', function() {
if (quiz.hasPrev) {
quiz.currentQuestion.setDefault()
}
updateQuizContainer(quiz.prev)
updateBtns()
})
btnNext.addEventListener('click', () => {
if (quiz.hasNext) {
quiz.currentQuestion.setDefault()
}
updateQuizContainer(quiz.next)
updateBtns()
})
btnResult.addEventListener('click', function() {
quiz.currentQuestion.setDefault()
console.log(urlParser(quiz))
})
})();
.d-inline-block {
display: inline-block;
}
.d-none {
display: none;
}
<div id="quiz-container"></div>
<div id="quiz-controls">
<button id="btn-prev" class="d-inline-block">
PREV
</button>
<button id="btn-next" class="d-inline-block">
NEXT
</button>
<button id="btn-result" class="d-none">
RESULT
</button>
</div>
<div id="result"></div>

Validate Duplicate Data Entry in Array - JavaScript

My problem is that I want to insert values that are not repeated when doing a push
This is my code :
addAddress: function() {
this.insertAddresses.Adress = this.address_address
this.insertAddresses.State = this.selectedStateAddress
this.insertAddresses.City = this.selectedCityAddress
if(this.insertAddresses.Adress !== "" && this.insertAddresses.State !== null && this.insertAddresses.City !== null) {
let copia = Object.assign({}, this.insertAddresses);
this.addresses.push(copia)
}
else
{
this.$message.error('Not enough data to add');
return
}
},
When adding a new element to my object, it returns the following.
When I press the add button again, it adds the same values again, I want to perform a validation so that the data is not the same. How could I perform this validation in the correct way?
Verify that the item doesn't already exist in the array before inserting.
You can search the array using Array.prototype.find:
export default {
methods: {
addAddress() {
const newItem = {
Address: this.address_address,
State: this.selectedStateAddress,
City: this.selectedCityAddress
}
this.insertItem(newItem)
},
insertItem(item) {
const existingItem = this.addresses.find(a => {
return
a.State === item.State
&& a.City === item.City
&& a.Address === item.Address
})
if (!existingItem) {
this.addresses.push(item)
}
}
}
}
On the other hand, if your app requires better performance (e.g., there are many addresses), you could save a separate dictonary to track whether the address already exists:
export default {
data() {
return {
seenAddresses: {}
}
},
methods: {
insertItem(item) {
const { Address, State, City } = item
const key = JSON.stringify({ Address, State, City })
const seen = this.seenAddresses[key]
if (!seen) {
this.seenAddresses[key] = item
this.addresses.push(item)
}
}
}
}
demo
check it:
let filter= this.addresses.find(x=> this.insertAddresses.State==x.State)
if (filter==null) {
this.$message.error('your message');
}
OR FILTER ALL
let filter= this.addresses.find(x=> this.insertAddresses.Adress==x.Adress && this.insertAddresses.State==x.State && this.insertAddresses.City==x.City)
if (filter==null) {
this.$message.error('your message');
}
``

object of array not update in state

I have form where user can add as much as he wants documents. Each document have several inputs.
And I'm trying to get each document inputs values and put it to state as array of objects.
State should look like:
[
{
id: 'UGN2WP68P1',
name: 'passport',
placeIssue: 'paris'
},
{
id: 'TD0KUWWIM6',
name: 'shengen visa',
placeIssue: 'paris'
}
...
]
So I write a function which is called on inputs change. He check are there object with same id, if there is no object with same id he creates new and add to array, if object exist with same id then he update object:
const addNewDocumentObj = (id, type, val) => {
// Get object with same id
let docObj = addedDocsArr.filter( el => el.id === id)
// If there is no object with same id, creates new one
if (docObj.length === 0) {
if (type === 'name'){
let obj = {
id: id,
docId: val.id
}
setAddedDocsArr(addedDocsArr.concat(obj))
} else if (type === 'placeIssue') {
let obj = {
id: id,
placeIssue: val
}
setAddedDocsArr(addedDocsArr.concat(obj))
}
// If object exist with same id then updates with new value and adds to array
} else {
if (type === 'name'){
let newObject = Object.assign(docObj, {name: val.id})
let newArray = addedDocsArr.filter(el => el.id !== id)
setAddedDocsArr(newArray.concat(newObject))
} else if (type === 'placeIssue') {
let newObject = Object.assign(docObj, {placeIssue: val})
let newArray = addedDocsArr.filter(el => el.id !== id)
setAddedDocsArr(newArray.concat(newObject))
}
}
}
But it doesn't work, and I can't understand why, maybe my logic is bad and there is better practise?
UPDATE:
In React debugger I noticed how state changes. If I add select document name, in state object looks like that:
{name: 'passport', id: 'UGN2WP68P1'}
If I enter document place of issue value. Then object changes and show data like that:
{placeIssue: 'paris', id: 'UGN2WP68P1'}
But result should be:
{name: 'passport', placeIssue: 'paris', id: 'UGN2WP68P1'}
So it looks like that object not updated but created new one
Maybe you need something like:
const addNewDocumentObj = (id, type, val) => {
// Get object with same id
let docObj = addedDocsArr.find(el => el.id === id)
// If there is no object with same id, creates new one
if (!docObj) {
docObj = { id, placeIssue: val }
// and pushes it to addedDocsArray
addedDocsArr.push(docObj)
}
if (type === 'name') {
docObj.name = val.id
} else if (type === 'placeIssue') {
docObj.placeIssue = val
}
setAddedDocsArr(addedDocsArr)
}
First of all, why are you using filter if you are actually try to find something in array? Just use find.
Second, if object with given id is already exists, there is no need to filter your array and then put that object back... Just find that object in array and update it! It is already in your array! Remember that Array contains references to your objects, so when you grab your object from the Array and edit it, your edit the same object that Array have.
Last one, Idk what logic your setAddedDocsArr function have. In my example I assume that the only thing it does is set its argument (newArray) to the variable named addedDocsArr. So instead of that, in situation where object with given id is not present, I just push it in old array.
Finished App:
Implementation of Handle submit:
const handleSubmit = (event) => {
event.preventDefault();
if (!uid) {
alert("Please enter the ID");
return;
}
let existingRecords = docs.filter((doc) => doc.id === uid);
if (!existingRecords.length) {
let newRecord = {
id: uid,
name: name,
issuePlace: place
};
setDocs([...docs, newRecord]);
setId("");
setName("");
setPlace("");
} else {
let unmodifiedRecords = docs.filter((doc) => doc.id !== uid);
if (name) {
existingRecords[0].name = name;
}
if (place) {
existingRecords[0].issuePlace = place;
}
unmodifiedRecords.push(existingRecords[0]);
setDocs(unmodifiedRecords);
setId("");
setName("");
setPlace("");
}
};
And Here is the full finished example:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [docs, setDocs] = useState([
{ id: "1", name: "passport", issuePlace: "delhi" }
]);
const [uid, setId] = useState("");
const [name, setName] = useState("");
const [place, setPlace] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!uid) {
alert("Please enter the ID");
return;
}
let existingRecords = docs.filter((doc) => doc.id === uid);
if (!existingRecords.length) {
let newRecord = {
id: uid,
name: name,
issuePlace: place
};
setDocs([...docs, newRecord]);
setId("");
setName("");
setPlace("");
} else {
let unmodifiedRecords = docs.filter((doc) => doc.id !== uid);
if (name) {
existingRecords[0].name = name;
}
if (place) {
existingRecords[0].issuePlace = place;
}
unmodifiedRecords.push(existingRecords[0]);
setDocs(unmodifiedRecords);
setId("");
setName("");
setPlace("");
}
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<table>
<tr>
<td>
<label>ID: </label>
</td>
<td>
<input
value={uid}
onChange={(e) => {
setId(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>
<label>Name: </label>
</td>
<td>
<input
value={name}
onChange={(e) => {
setName(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>
<label>Isuue Place: </label>
</td>
<td>
<input
value={place}
onChange={(e) => {
setPlace(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
{docs.map((doc) => (
<div className="records">
<span>{"ID:" + doc.id + " "}</span>
<span>{"Name:" + doc.name + " "}</span>
<span>{"Issue Place:" + doc.issuePlace + " "}</span>
</div>
))}
</div>
);
}
Check out finished example with source code at: Codesandbox Link
I find a pretty easy way how to solve this problem. I read documentations of react forms and find multiple inputs idea React Forms
So I changed my code to:
// Update or add information of added documents inputs
const addNewDocumentObj = (id, e, name) => {
const newInput = addedDocsArr.map(el => {
if(id === el.id) {
if(name === 'name'){
el[name] = e.target.value
} else if (name === 'placeIssue'){
el[name] = e.target.value
}
}
return el
})
setAddedDocsArr(newInput);
}
// Add new document inputs
const addNewDocument = () => {
let blockId = randomNumber(10, true, false)
setAddedDocsArr([...addedDocsArr, {id: blockId, name: '', placeIssue: ''}])
}
And it works perfectly!

Issues printing my groups tree in nodeJS app

I'm trying to print all created groups and they're children so it'll look like that:
[ [ 'Father1', 'Child1', 'Child2', 'Child3' ],
[ 'Father1', 'Child1', 'Child4' ],
[ 'Father1', 'Child1', 'Child5' ] ]
The problems I encountered are varied. from:
var keys = name.keys(o); ^ TypeError: name.keys is not a function to total stack overflow, iv'e debugged the printPath function and it's doing it's job separately but not with my final tree structure.
My tree and print function looks like that:
groups.js:
class groups {
constructor() {
this.root = new Group('root');
}
printPath(name){
this.root.getPath(name)
}
group.js:
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null;
this.children = [];
this.users = new users || null;
}
getPath(name) {
function iter(o, p) {
var keys = name.keys(o);
if (keys.length) {
return keys.forEach(function (k) {
iter(o[k], p.concat(k));
});
}
result.push(p);
}
var result = [];
iter(name, []);
return result;
}
Edit:
For creating a group i'm using a menu handler function:
function createGroup(callback) {
rl.question('Add name for father group: \n', (parent) => {
let parentGroup = programdata.groups.findGroupByName(parent);
if (!parentGroup) {
parentGroup = programdata.groups.root;
}
rl.question('name of new group\n', (groupName) => {
parentGroup.setChildren(new Group(groupName, parentGroup));
console.log(parentGroup);
callback();
});
})
}
findGroupByNameis a nice recursion i made that finds nested groups (feel free to use!) sitting in class groups.
findGroupByName(name) {
if (!name) return null;
return this._findGroupByNameInternal(this.root, name);
}
_findGroupByNameInternal(group, name) {
if (!group) return null;
if (group.name === name) return group;
for (const g of group.children) {
const result = this._findGroupByNameInternal(g, name);
if (!result) continue;
return result;
}
}
And setChildren function placed in class Group:
setChildren(child) {
this.children.push(child);
}
EDIT:
Thank you for the answer, could you please help me realize your method in my menu handler? iv'e tried this: and it giving me nothing.
function createGroup(callback) {
rl.question('Add name for father group: \n', (parent) => {
let parentGroup = programdata.groups.findGroupByName(parent);
let treePath = Group.root.printPath();
if (!parentGroup) {
parentGroup = programdata.groups.root;
}
rl.question('name of new group\n', (groupName) => {
parentGroup.addChild(new Group(groupName, parentGroup));
console.log(treePath);
callback();
});
})
}
The root cause you got the error TypeError: name.keys is not a function is that a string is passed into getPath(name) as argument name, you know the JS string object doesn't have a function property keys.
I refactor your code and fix some error, here is the testable version. Pls put them into the same folder and run test.js.
group.js
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null; // Point to this group's father
this.children = []; // Children of this group, can be sub-group or string
if (!!parent) { // Link to the father
parent.addChild(this);
}
// this.users = new users || null; // Useless, remove it.
}
addChild(...args) {
for(let o in args) {
this.children.push(args[o]);
}
}
/**
* Recursion to build the tree
* #param group
* #returns {*}
*/
iter(group) {
let children = group.children;
if (Array.isArray(children)) { // If the child is a group
if (children.length > 0) {
let result = [];
result.push(group.name);
for (let child of children) {
result.push(group.iter(child));
}
return result;
}
else {
return [];
}
}
else { // If the group is a string
return group;
}
}
getPath() {
return this.iter(this);
}
}
module.exports = Group;
groups.js
let Group = require('./group');
class Groups {
constructor() {
this.root = new Group('root');
}
printPath() {
return this.root.getPath();
}
}
module.exports = Groups;
test.js
let Group = require('./group');
let Groups = require('./groups');
// Root
let rootGroups = new Groups();
// Group 1
let group1 = new Group('Father1', rootGroups.root);
group1.addChild('Child1', 'Child2', 'Child3');
// Group 2
let group2 = new Group('Father1', rootGroups.root);
group2.addChild('Child1', 'Child4');
// Group 3
let group3 = new Group('Father1', rootGroups.root);
group3.addChild('Child1', 'Child5');
let treePath = rootGroups.printPath();
console.log(treePath);
The output is:
[ 'root',
[ 'Father1', 'Child1', 'Child2', 'Child3' ],
[ 'Father1', 'Child1', 'Child4' ],
[ 'Father1', 'Child1', 'Child5' ] ]
Process finished with exit code 0
Enjoy it :)
Ok, found a solution.
Treeshow(){
var node = this.root;
var depth = '-'
recurse( node );
function recurse( node) {
depth +='-'
console.log(depth+node.name);
for (var child in node.children ) {
recurse(node.children[child]);
}
depth = depth.slice(0, -1);
}
}
that will show my tree just like that:
--root
---FooFather
----BarSemiFather
-----FooChild
------BarBaby

How can i append table data value in ng-repeat using angularjs

I have two table. dynamicaly data will come for table one after I click the dynamic table data button. after I click the done button I want to
append the data in $scope.notiData.
now after I click done button $scope.notiData data is gone. every time data is coming from tableTwo what is there in presently. so how can i use concat Iin $scope.notiData.please help.
http://jsfiddle.net/A6bt3/127/
Js
var app = angular.module('myApp', []);
function checkBoxCtrl($scope) {
$scope.notiData = [];
$scope.tableOne = [{
firstname: 'robert',
value: 'a'
}, {
firstname: 'raman',
value: 'b'
}, {
firstname: 'kavi',
value: 'c'
}, {
firstname: 'rorank',
value: 'd'
}
];
$scope.tableOne1 = [{
firstname: 'robvzxcvert',
value: 'a'
}, {
firstname: 'ramsdgan',
value: 'b'
}, {
firstname: 'kasdgsdgvi',
value: 'c'
}, {
firstname: 'rordggank',
value: 'd'
}
];
$scope.tableTwo = [];//the table to be submitted
function removeitems(tableRef) { //revmove items from tableRef
var i;
for (i = tableRef.length - 1; i >= 0; i -= 1) {
if (tableRef[i].checked) {
tableRef.splice(i, 1);
}
}
}
$scope.btnRight = function () {
//Loop through tableone
$scope.tableOne.forEach(function (item, i) {
// if item is checked add to tabletwo
if (item.checked) {
$scope.tableTwo.push(item);
}
})
removeitems($scope.tableOne);
}
$scope.btnAllRight = function () {
$scope.tableOne.forEach(function (item, i) {
item.checked = true;
$scope.tableTwo.push(item);
})
removeitems($scope.tableOne);
}
$scope.btnLeft = function () {
$scope.tableTwo.forEach(function (item, i) {
if (item.checked) {
$scope.tableOne.push(item);
}
})
removeitems($scope.tableTwo);
}
$scope.btnAllLeft = function () {
$scope.tableTwo.forEach(function (item, i) {
item.checked = true;
$scope.tableOne.push(item);
})
removeitems($scope.tableTwo);
}
$scope.done = function () {
angular.extend($scope.notiData, $scope.tableTwo);
$scope.tableTwo = [];
}
$scope.removeRow = function (item) {
var index = $scope.notiData.indexOf(item);
$scope.notiData.splice(index, 1);
}
$scope.dynamicTable= function () {
$scope.tableOne1.forEach(function (item, i) {
item.checked = true;
$scope.tableOne.push(item);
})
}
};
I want to append the data in $scope.notiData. now after I click done button $scope.notiData data is gone
The angular.extend replaces existing entries. To append, use array.concat:
$scope.done = function () {
//angular.extend($scope.notiData, $scope.tableTwo);
$scope.notiData = $scope.notiData.concat($scope.tableTwo);
$scope.tableTwo = [];
}
Also to avoid duplicate in ng-repeat use track by errors, use angular.copy to push items:
$scope.dynamicTable= function () {
$scope.tableOne1.forEach(function (item, i) {
item.checked = true;
//$scope.tableOne.push(item);
$scope.tableOne.push(angular.copy(item));
});
};
The ng-repeat directive tracks array objects by reference. Pushing duplicate objects will result in tracking errors. The angular.copy will create a new unique object reference for the item and will avoid the tracking errors.
The DEMO on JSFiddle.

Categories