Skip to content

Instantly share code, notes, and snippets.

@oceangravity
Created June 19, 2018 12:04
Show Gist options
  • Save oceangravity/cfe100588222780ccb9b4cb68a031161 to your computer and use it in GitHub Desktop.
Save oceangravity/cfe100588222780ccb9b4cb68a031161 to your computer and use it in GitHub Desktop.
<biblioteca>
<libro>
<nombre>Mastering Gradle</nombre>
<autor>Mainak Mitra</autor>
</libro>
<libro>
<nombre>Mastering GitHub</nombre>
<autor>Mainak Mitra</autor>
</libro>
<libro>
<nombre>Building Microservices</nombre>
<autor>Sam Newman</autor>
</libro>
<libro>
<nombre>Javascript Frontier</nombre>
<autor>Sam Newman</autor>
</libro>
<libro>
<nombre>Works</nombre>
<autor>Sam Newman</autor>
</libro>
</biblioteca>
// Obtenemos los elementos
const books = document.querySelectorAll('biblioteca > libro');
let structure = {model:[]};
// Necesario en caso de que ya exista el author
const checkAuthor = (author) => {
return structure.model.findIndex((book) => {
return book.author.match(new RegExp(author));
});
};
// Recorremos y agregamos a la estructura
books.forEach((book) => {
const authorName = book.querySelector('autor').innerHTML;
const bookName = book.querySelector('nombre').innerHTML;
let authorExist = checkAuthor(authorName);
if(authorExist > -1){
structure.model[authorExist].books.push(bookName);
}else{
structure.model.push({
author: authorName,
books: [bookName]
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment