I have an array called productsthat is structured like:
{
"_id": "150",
"name": "Milk",
"description": "Skimmed",
"price": "10",
"ratings": [
{
"email": "xyz#mail.com",
"rating": "5"
},
{
"email": "abc#mail.com",
"rating": "3"
},
{
"email": "def#mail.com",
"rating": "1"
},
]
},
{
"_id": "151",
...
...
...
I want to calculate the average rating of a product and display it on page load, using Vue.js.
My HTML page for products has a v-for = "(product, key) in products" Which I use to display all the products by name,desc etc.
Any help will be appreciated.
Thanks in advance.
You can try:
new Vue({
el: '#app',
data() {
return {
products: [
{
"_id": "150",
"name": "Milk",
"description": "Skimmed",
"price": "10",
"ratings": [
{
"email": "xyz#mail.com",
"rating": "5"
},
{
"email": "abc#mail.com",
"rating": "3"
},
{
"email": "def#mail.com",
"rating": "1"
},
]
}
]
}
},
mounted () {
// mapping each item of products to merge averageRating calculated
this.products = this.products.map(product => {
// ratings summation
const totalRatings = product.ratings.reduce((acc, { rating }) => acc += Number(rating), 0)
const averageRating = totalRatings/product.ratings.length
// returning the merge of the current product with averageRating
return {...product, averageRating}
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<ul>
<li v-for = "(product, key) in products" :key="key">
name: {{ product.name }} ~ averageRating: {{ product.averageRating }}
</li>
</ul>
</div>
Try like below,
products = [
// The above array data ..
];
this.modifiedProducts = products.map(product => {
const average = product.ratings.reduce((total, next) => total + parseInt(next.rating), 0) / product.ratings.length;
return {
...product,
averageRating: average.toFixed(2)
}
});
.html
<ul>
<li v-for="product in modifiedProducts">
name: {{ product.name }} ~ AverageRating: {{ product.averageRating }}
</li>
</ul>
you can also use a simple javascript code where you can use a for loop to do that as well...
<script>
let ratingSum = 0
let myArray ={
_id: "150",
name: "Milk",
description: "Skimmed",
price: "10",
ratings: [
{
email: "xyz#mail.com",
rating: "5"
},
{
email: "abc#mail.com",
rating: "3"
},
{
email: "def#mail.com",
rating: "1"
},
]
}
// stringify your array as json array
var jsonArray = JSON.stringify(myArray)
// get the array length
var myArraylength = myArray.ratings.length
// use a for loop to loop through the array and sum all the ratings
for(i=0; i< myArray.ratings.length; i++){
ratingSum += parseInt(myArray.ratings[i].rating)
}
// after getting the sum of the rating divide it on the array length
myAverage = ratingSum / myArray.ratings.length
console.log(myAverage)
</script>
Related
For one of my e-commerce application requirement, I have a nested array of the form (Sample):
const data = [
{
"id": 1,
"group": "upper-wear",
"labels": [
{
"type": "shirts",
"quantity": "20",
},
],
popular: true
},
{
"id": 2,
"group": "bottom-wear",
"lables": [
{
"type": "trousers",
"quantity": "31",
},
],
popular: true
},
]
To this array, I need to insert new objects to the array 'labels' if the group value equals 'upper-wear'.
const newDataToInsert = [
{
"type": 'blazers',
"quantity": 19
},
]
This is what I tried so far, considering that for now I only need to insert to single label (i.e. 'upper-wear') (in future, there can be multiple labels category 'upper-wear', 'bottom-wear', to be inserted into):
const updatedArray = data.map((datum) => {
if (datum.group === 'upper-wear') {
return {
...datum,
labels: [...datum.labels, ...newDataToInsert]
};
}
});
console.log(updatedArray);
But there seems to be a silly issue that I am missing as the result returns like this:
[
{
id: 1,
group: 'upper-wear',
labels: [ [Object], [Object] ],
popular: true
},
undefined
]
I know there may be better approaches available, but this is what I can think of as the minimum solution for now.
any help to resolve the current or any better solution will be highly appreciated.
Try with this
updatedArray = data.map((d) => {
if (d.group && d.group === 'upper-wear') {
return { ...d, labels: d.labels.concat(newDataToInsert) }
} else {
return d;
}
})
const data = [
{
"id": 1,
"group": "upper-wear",
"labels": [
{
"type": "shirts",
"quantity": "20",
},
],
popular: true
},
{
"id": 2,
"group": "bottom-wear",
"lables": [
{
"type": "trousers",
"quantity": "31",
},
],
popular: true
},
];
const newDataToInsert = [
{
"type": 'blazers',
"quantity": 19
},
];
const updatedArray = data.map((d) => {
if (d.group && d.group === 'upper-wear') {
return { ...d, labels: d.labels.concat(newDataToInsert) }
} else {
return d;
}
});
console.log(updatedArray)
Explaination
Here while mapping the data, we check for the condition
IF
If it matches then we will first copy the whole object from the variable b return { ...b }
after that we take another variable with the same name lables return { ...d, labels: d.labels.concat(newDataToInsert) },As per the JSON default nature the new variable with the same name will hold the latest value
Here in labels we first take a copy of old data and then merge it with newDataToInsert array labels: d.labels.concat(newDataToInsert), It will merge 2 arrays and store them in JSON with the name labels
Else
In else we just return the current values else { return d; }
You don't actually need to iterate with map over the array. Just find an object in the array and change what you want.
const data=[{id:1,group:"upper-wear",labels:[{type:"shirts",quantity:"20"}],popular:true},{id:2,group:"bottom-wear",lables:[{type:"trousers",quantity:"31"}],popular:true}];
const newDataToInsert=[{type:"blazers",quantity:19}];
data.find(({ group }) => group === 'upper-wear')?.labels.push(...newDataToInsert);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're not returning all objects from your map. you're only returning a result when your criteria is met. This is resulting in your undefined objects...
const data = [
{ "id": 1, "group": "upper-wear", "labels": [ { "type": "shirts", "quantity": "20", }, ], popular: true },
{ "id": 2, "group": "bottom-wear", "lables": [ { "type": "trousers", "quantity": "31", }, ], popular: true },
]
const newDataToInsert = [ { "type": 'blazers',"quantity": 19 }, ]
const updatedArray = data.map(datum => {
if (datum.group === 'upper-wear') datum.labels = [...datum.labels, ...newDataToInsert]
return datum
});
console.log(updatedArray);
You can use Array#find to locate the desired group and then change labels for the group found. There are two options depending on how many items you would like to insert. Use Array#push to add the desired item; use forEach for more than one item:
const searchgroup = "upper-wear";
const target = data.find(({group}) => group === searchgroup);
target.labels.push(...newDataToInsert); //For one item to insert
//newDataToInsert.forEach(label => target.labels.push( label )); //For more than one item
const data = [{"id": 1, "group": "upper-wear", "labels": [{"type": "shirts", "quantity": "20"},],popular: true }, {"id": 2, "group": "bottom-wear", "lables": [{"type": "trousers", "quantity": "31", },],popular: true}];
const newDataToInsert = [{"type": 'blazers', "quantity": 19}];
//group to find
const searchgroup = "upper-wear";
//target element in data
const target = data.find(({group}) => group === searchgroup);
//check if group was found
if( target ) {
//if there's only one product in newDataToInsert us this:
//target.labels.push(...newDataToInsert);
//if you have more than one product to be inserted use this; also works for one
newDataToInsert.forEach(label => target.labels.push( label ));
} else {
console.log( `No such group found: ${searchgroup}!` );
}
console.log( data );
This is my object
let products = [
{ "productName": "A", "storage": "Lot 1", "quantity": 1000, "status": "stockIn" },
{ "productName": "A", "storage": "Lot 1", "quantity": 100, "status": "stockIn" },
{ "productName": "A", "storage": "Lot 1", "quantity": 500, "status": "stockOut" },
{ "productName": "A", "storage": "Lot 2", "quantity": 500, "status": "stockIn" }
]
This is what I am trying to achieve
let result = [
{ "productName": "A", "storage": "Lot 1", "stockIn": 1100, "stockOut": 500, "available":600 },
{ "productName": "A", "storage": "Lot 2", "stockIn": 500, "stockOut": 0, "available":500 }
]
Please kindly provide an idea on how to achieve this without redundant codes. Thanks
var storage = new Set(products.map(item => item.storage));
storage.forEach(lot => {
var stockIn = products.filter(item => item.storage === storage && item.status == 'stockIn')
.map(({ storage, quantity }) => ({ storage, quantity }));
var stockInSum = stockIn.reduce((prev, curr, index) => prev + curr.quantity, 0);
var stockOut = products.filter(item => item.storage === storage && item.status == 'stockOut')
.map(({ storage, quantity }) => ({ storage, quantity }))
var stockOutSum = stockOut.reduce((prev, curr, index) => prev + curr.quantity, 0);
}
Using Array#reduce, iterate over the array while updating a Map where the key is the combination of productName and storage, and the value is the corresponding grouped object
In every iteration, using the current key, get the pair if exist and deconstruct stockIn and stockOut. According to the current status, update one of the latter values and compute available. Finally, using Map#set, create/update the pair.
Using Map#values, get the list of grouped objects
const products = [
{ productName: "A", storage: "Lot 1", quantity: 1000, status: "stockIn" },
{ productName: "A", storage: "Lot 1", quantity: 100, status: "stockIn" },
{ productName: "A", storage: "Lot 1", quantity: 500, status: "stockOut" },
{ productName: "A", storage: "Lot 2", quantity: 500, status: "stockIn" }
];
const result = [...
products.reduce((map, { productName, storage, quantity, status }) => {
const key = `${productName}-${storage}`;
let { stockIn = 0, stockOut = 0 } = map.get(key) ?? {};
if(status === 'stockIn') stockIn += quantity;
else stockOut += quantity;
const available = stockIn - stockOut;
map.set(key, { productName, storage, stockIn, stockOut, available });
return map;
}, new Map)
.values()
];
console.log(result);
Here is the general pattern. I will leave it to you to figure out the other fields.
const reduced = products.reduce( (a,v) => {
const found = a.find(it=>it.lot === v.lot && it.productName === v.productName)
if (found) {
a.quantity += v.quantity
// aggregate your other fields here.
}
else {
a.push(v)
}
return a
}, [] )
I am trying to calculate the average duration for each stage. So in the array below - I should be able to get the average duration for 'test1', which would be 2.
jobs = [
{
"build_id": 1,
"stage_executions": [
{
"name": "test1"
"duration": 1,
},
{
"name": "test2"
"duration": 16408,
},
{
"name": "test3"
"duration": 16408,
},
]
},
{
"build_id": 2,
"stage_executions": [
{
"name": "test1"
"duration": 3,
},
{
"name": "test2"
"duration": 11408,
},
{
"name": "test3"
"duration": 2408,
},
]
}
]
My failed attempt:
avgDuration: function(jobs) {
let durationSum = 0
for (let item = 0; item < this.jobs.length; item++) {
for (let i = 0; i < this.jobs[item].stage.length; item++) {
durationSum += stage.duration
}
durationAverage = durationSum/this.jobs[item].stage.length
}
return durationAverage
What am I doing wrong? I'm not sure how to accomplish this since the duration is spread out between each job.
UPDATE:
This is return a single average for all stages rateher than per stage
<template>
<div class="stages">
<h3>
Average Duration
</h3>
<table>
<tbody>
<tr v-for="item in durations">
<td>
<b>{{ item.average}} {{ item.count }}</b>
// this returns only 1 average and 177 count instead of 10
<br />
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { calculateDuration } from "../../helpers/time.js";
import { liveDuration } from "../../helpers/time.js";
import moment from "moment";
export default {
name: "Stages",
data() {
return {
jobs: [],
durations: []
};
},
methods: {
avgDuration: function(jobs) {
var averageByName = {}; // looks like { 'name': { average: 111, count: 0 }}
for (var job of jobs) {
for(var stage of job.stage_execution) {
if (averageByName[stage.name] == null) { // we need a new object
averageByName[stage.name] = { average: 0, count: 0 };
}
// just name it so its easier to read
var averageObj = averageByName[stage.name];
// update count
averageObj.count += 1;
// Cumulative moving average
averageObj.average = averageObj.average + ( (stage.duration - averageObj.average) / averageObj.count );
console.log(averageObj.count)
}
}
return averageByName
},
},
created() {
this.JobExecEndpoint =
process.env.VUE_APP_TEST_URL +
"/api/v2/jobs/?limit=10";
fetch(this.JobExecEndpoint)
.then(response => response.json())
.then(body => {
for (let i = 0; i < body.length; i++) {
this.jobs.push({
name: body[i].job.name,
job: body[i].job,
stage_execution: body[i].stage_executions,
});
}
})
.then(() => {
this.$emit("loading", true);
})
.then(() => {
this.durations = this.avgDuration(this.jobs);
})
.catch(err => {
console.log("Error Fetching:", this.JobExecEndpoint, err);
return { failure: this.JobExecEndpoint, reason: err };
});
}
};
</script>
We can do this pretty simply and without overflow from having too many numbers by using a Cumulative moving average and a few loops.
Here is a line the relevant Wikipedia page on Moving Averages and the most relvant formula below.
I will not go into much detail with the above as there are a lot of documents describing this sort of thing. I will however say that the main reason to this over adding all the values together is that there is a far lower chance of overflow and that is why I am using it for this example.
Here is my solution with comments made in code.
var jobs = [ { "build_id": 1, "stage_executions": [ { "name": "test1", "duration": 1, }, { "name": "test2", "duration": 16408, }, { "name": "test3", "duration": 16408, }, ] }, { "build_id": 2, "stage_executions": [ { "name": "test1", "duration": 3, }, { "name": "test2", "duration": 11408, }, { "name": "test3", "duration": 2408, }, ] } ];
var averageByName = {}; // looks like { 'name': { average: 111, count: 0 }}
for (var job of jobs) {
for(var stage of job.stage_executions) {
if (averageByName[stage.name] == null) { // we need a new object
averageByName[stage.name] = { average: 0, count: 0 };
}
// just name it so its easier to read
var averageObj = averageByName[stage.name];
// update count
averageObj.count += 1;
// Cumulative moving average
averageObj.average = averageObj.average + ( (stage.duration - averageObj.average) / averageObj.count );
}
}
// print the averages
for(var name in averageByName) {
console.log(name, averageByName[name].average);
}
Let me know if you have any questions or if anything is unclear.
You could collect the values in an object for each index and map later only the averages.
var jobs = [{ build_id: 1, stage_executions: [{ name: "test1", duration: 1 }, { name: "test2", duration: 16408 }, { name: "test3", duration: 16408 }] }, { build_id: 2, stage_executions: [{ name: "test1", duration: 3 }, { name: "test2", duration: 11408 }, { name: "test3", duration: 2408 }] }],
averages = jobs
.reduce((r, { stage_executions }) => {
stage_executions.forEach(({ duration }, i) => {
r[i] = r[i] || { sum: 0, count: 0 };
r[i].sum += duration;
r[i].avg = r[i].sum / ++r[i].count;
});
return r;
}, []);
console.log(averages.map(({ avg }) => avg));
console.log(averages);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I've used Array.prototype.flatMap to flatten the jobs array into an array of {name:string,duration:number} object. Also, to make more solution a bit more dynamic the function takes in a field argument which returns the average for that specific field.
const jobs = [
{
"build_id": 1,
"stage_executions": [
{
"name": "test1",
"duration": 1,
},
{
"name": "test2",
"duration": 16408,
},
{
"name": "test3",
"duration": 16408,
},
]
},
{
"build_id": 2,
"stage_executions": [
{
"name": "test1",
"duration": 3,
},
{
"name": "test2",
"duration": 11408,
},
{
"name": "test3",
"duration": 2408,
},
]
}
];
const caller = function(jobs, field) {
const filtered = jobs
.flatMap((item) => item.stage_executions)
.filter(item => {
return item.name === field;
})
const total = filtered.reduce((prev, curr) => {
return prev + curr.duration;
}, 0)
return total / filtered.length;
}
console.log(caller(jobs, 'test1'))
console.log(caller(jobs, 'test2'))
console.log(caller(jobs, 'test3'))
In case you get the error flatMap is not a function. You can add this code snippet in your polyfill or at the top of your js file.
Array.prototype.flatMap = function(lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};
PS: for demostration, I obtained the flatMap implementation from here
I am building a select dropdown input for a webpage. I want to make a 'popular' options group which appears at the top of the dropdown.
I am working with data in the following structure.
I need to find a way to reorder the items inside the people array based on their name.
For example moving:
pogo-stick from toys[2] -> toys[0]
cards from toys[3] to toys [2]
I will have an array of popular toys such as:
popularToys: [
"cards", "pogo-stick"
]
How can I iterate through the array of objects and move them in to the new order?
Data:
{
"toys": [
{
"name": "car",
"price": "10"
},
{
"name": "duck",
"price": "25"
},
{
"name": "pogo-stick",
"price": "60"
},
{
"name": "cards",
"price": "5"
}
]
}
Use forEach() loop where you can find the index of the toy object and swap:
var popularToys = [
"cards", "pogo-stick"
]
var data = {
"toys": [
{
"name": "car",
"price": "10"
},
{
"name": "duck",
"price": "25"
},
{
"name": "pogo-stick",
"price": "60"
},
{
"name": "cards",
"price": "5"
}
]
};
popularToys.forEach(function(toy, index){
var toyObjIndex = data.toys.findIndex(x => x.name==toy);
//swap
var tempObj = data.toys[toyObjIndex];
data.toys[toyObjIndex] = data.toys[index];
data.toys[index] = tempObj;
});
console.log(data);
Using a combination of map and filter we are able to split the required logic into to methods (Maybe more readable)
Popular() returns a filtered Array of any of the toy items that have a name property that corresponds with the current name in the iteration of popular
Rest() returns a filtered Array of toys where the name property of the toy in the iteration does not exist in the Array of String in popular
const toys = [
{
name: 'car',
price: '10'
},
{
name: 'exception',
price: '999999'
},
{
name: 'duck',
price: '25'
},
{
name: 'pogo-stick',
price: '60'
},
{
name: 'cards',
price: '5'
},
{
name: 'another !exception',
price: '100000'
},
{
name: 'pogo-stick',
price: 'A MILLION POUNDS'
},
{
name: 'duck',
price: '100'
}
]
const popular = [
'cards',
'pogo-stick',
'car',
'duck'
]
const Popular = () => {
return [].concat(...popular.map(n => toys.filter(({name}) => name === n)))
}
const Rest = () => toys.filter(({name}) => popular.indexOf(name) === -1)
let ordered = [].concat(...Popular(), ...Rest())
console.log(ordered)
You could use a custom sort function
var popularToys = [
"cards", "pogo-stick"
]
var data = {
"toys": [
{
"name": "car",
"price": "10"
},
{
"name": "duck",
"price": "25"
},
{
"name": "pogo-stick",
"price": "60"
},
{
"name": "cards",
"price": "5"
}
]
};
function popularFirst(a, b) {
var aIsPopular = popularToys.indexOf(a.name) > -1;
var bIsPopular = popularToys.indexOf(b.name) > -1;
if (aIsPopular) {
// b could be popular or not popular, a still comes first
return -1;
} else if (bIsPopular) {
// a isnt popular but b is, change the order
return 1;
} else {
// no change
return 0;
}
}
console.log(data.toys.sort(popularFirst));
function compare(a,b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
toys.sort(compare);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
I'd like to map this table's chapter_id and brother_id with the brothers and chapters table below and return the brothername and name field's respectively. Using js or jquery. I am using vuejs returning minutes array as a computed property. See below.
In sql it's be something like
select brothername from brothers where minute.brother_id = brothers.id ... and then set the brothername as the new value for brother_id
same thing goes for chapter_id:
select brothername from brothers where minute.brother_id = brothers.id ... and then set the brothername as the new value for brother_id
the resulting array or object should be:
Expected Array
[
{
"location":"UCLA",
"chapter_id":"Beta",
"brother_id":"Golpher",
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
},
{ ... },
{
"location":"John's Deli",
"chapter_id":"Beta", notice the change in the array based on the ids
"brother_id":"Sheera", notice the change in the array based on the ids
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
}
]
Minutes Table (original array)
[
{
"location":"UCLA",
"chapter_id":2,
"brother_id":1,
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
},
{ ... },
{
"location":"John's Deli",
"chapter_id":2,
"brother_id":4,
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
}
]
Chapter's Table
[
{
"id":1,
"letter_representation":"A",
"name":"Alpha",
"founded_at":"UCLA",
...
},
{ ... }
]
Brother's Table
[
{
"id":1,
"profile_id":1,
"chapter_id":1,
"brothername":"Golpher",
"firstname":"Jack",
...
},
{ ... },
{
"id":4,
"profile_id":4,
"chapter_id":1,
"brothername":"Sheera",
"firstname":"Jake",
...
}
]
Vue.js
computed: {
brothers () {
return this.$store.state.brothers
},
chapters () {
return this.$store.state.chapters
},
minutes () {
return this.$store.getters.model
}
},
I assume that you don't want to mutate objects in the original arrays with this operation.
Note You may want to handle the case where brother_id or chapter_id doesn't exist in the corresponding table. In the below example, it just sets the property value to undefined
const minutesTable = [{
"location": "UCLA",
"chapter_id": 2,
"brother_id": 1,
"created_at": "2008-05-15 22:23:00",
"status": "Approved"
}, {
"location": "John's Deli",
"chapter_id": 2,
"brother_id": 4,
"created_at": "2008-05-15 22:23:00",
"status": "Approved"
}]
const chapterTable = [{
"id": 1,
"letter_representation": "A",
"name": "Alpha",
"founded_at": "UCLA",
}]
const brotherTable = [{
"id": 1,
"profile_id": 1,
"chapter_id": 1,
"brothername": "Golpher",
"firstname": "Jack",
}, {
"id": 4,
"profile_id": 4,
"chapter_id": 1,
"brothername": "Sheera",
"firstname": "Jake",
}]
// your result
const result = minutesTable.map(m => {
const brother = brotherTable.find(b => b.id === m.brother_id)
const chapter = chapterTable.find(c => c.id === m.chapter_id)
return Object.assign({}, m, {
brother_id: brother && brother.brothername,
chapter_id: chapter && chapter.name,
})
})
console.log(result)
This should be what you need
const minutesTable = [
{
"location":"UCLA",
"chapter_id":2,
"brother_id":1,
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
},
{
"location":"John's Deli",
"chapter_id":2,
"brother_id":4,
"created_at":"2008-05-15 22:23:00",
"status":"Approved"
}
]
const chapterTable =
[
{
"id":1,
"letter_representation":"A",
"name":"Alpha",
"founded_at":"UCLA",
}
]
const brotherTable = [
{
"id":1,
"profile_id":1,
"chapter_id":1,
"brothername":"Golpher",
"firstname":"Jack",
},
{
"id":4,
"profile_id":4,
"chapter_id":1,
"brothername":"Sheera",
"firstname":"Jake",
}
]
/* code starts here */
let newMinutesTable = JSON.parse(JSON.stringify(minutesTable)).map(a => {
let brother = brotherTable.find(id => id.id === a.brother_id);
let chapter = chapterTable.find(id => id.id === a.chapter_id)
if (brother) a.brother_id = brother.brothername
if (chapter) a.chapter_id = chapter.name;
return a;
})
console.log([minutesTable,newMinutesTable]);
I think you should prepare those values first just to better understanding. So I made this, let me explain in pieces.
Your input information:
var minutesTable = [{
"location": "UCLA",
"chapter_id": 2,
"brother_id": 1,
"created_at": "2008-05-15 22:23:00",
"status": "Approved"
}, {
"location": "John's Deli",
"chapter_id": 2,
"brother_id": 4,
"created_at": "2008-05-15 22:23:00",
"status": "Approved"
}],
chapterTable = [{
"id": 1,
"letter_representation": "A",
"name": "Alpha",
"founded_at": "UCLA",
}],
brotherTable = [{
"id": 1,
"profile_id": 1,
"chapter_id": 1,
"brothername": "Golpher",
"firstname": "Jack",
}, {
"id": 4,
"profile_id": 4,
"chapter_id": 1,
"brothername": "Sheera",
"firstname": "Jake",
}];
Somehow you'll be forced to take this information as variables. We will work with that.
Preparing data
Dealing with array of objects it's a litle bit complicated when you need to look for unique informations on each object from distinct arrays especially if you want to run this more than once. So instead of working with arrays of objects we can save our lifes changing that to objects of objects, where each item index must be that unique IDs. Look:
var chapters = {},
brothers = {};
chapterTable.map(function(el, i) {
chapters[el.id] = el;
});
brotherTable.map(function(el, i) {
brothers[el.id] = el;
});
Now you can easily find a chapter by chapter_id or a brother by brother_id, right? Then you can finish the problem like this:
var output = [];
minutesTable.map(function(el, i) {
var item = {
"location": el.location, // note that values are just default values, just in case
"chapter_id":"-",
"brother_id":"-",
"created_at": el.created_at,
"status": el.status
};
// PS: you need to check if that brother_id really exists!
if(brothers[el.brother_id] != undefined) {
item.brother_id = brothers[el.brother_id].brothername;
}
// PS: the same with chapters
if(chapters[el.chapter_id] != undefined) {
item.chapter_id = chapters[el.chapter_id].name;
}
output.push(item);
});
That's it. Anyway, if you can change your SQL queries, would be better to work with SQL joins and prepare your values there.