Summing up value in array of objects - javascript

[
{
"id": {
"extId": "112",
"year": "2000"
},
"Count": 1
},
{
"id": {
"extId": "113",
"year": "2001"
},
"Count": 446
},
{
"id": {
"extId": "115",
"year": "2000"
},
"Count": 742
}, ...
]
I have a very long array of objects. I need to sum up the count based on the year. For e.g, I would like something like [{2000: 743}, {2001: 446},...].
I am not sure how to proceed with that in javascript. Should I loop through every object in the array and check for the year or is there some javascript function which can make this simpler.
Thanks.

You can use Array.reduce():
let countByYear = objects.reduce((acc, next) => {
acc[next.id.year] = (acc[next.id.year] || 0) + next.Count;
return acc;
}, {});
Note, this will produce a different structure from your example (because I read your question too sloppily):
{
2000: 743,
2001: 446
}
However I would say this is easier to work with than [ { 2000: 743 }, { 2001: 446 } ], since in that case you have an array of objects, that each have a single key, and you have no way of knowing what that key is, which I'd imagine makes it really difficult to iterate over them.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

You can use reduce:
arr.reduce((result, current) => {
result.push({[current.year]: current.Count});
return result
}, [])
This will give you this structure [{2000: 743}, {2001: 44}] and you can even do arr.filter(filterFn) first if you need to filter only certain years

You could use a Map and take the key/values for an array of objects.
var data = [{ id: { extId: "112", year: "2000" }, Count: 1 }, { id: { extId: "113", year: "2001" }, Count: 446 }, { id: { extId: "115", year: "2000" }, Count: 742 }],
count = Array.from(
data.reduce(
(m, { id: { year }, Count }) => m.set(year, (m.get(year) || 0) + Count),
new Map
),
([year, count]) => ({ [year]: count })
);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

<script>
var arr=[
{
"id": {
"extId": "112",
"year": "2000"
},
"Count": 1
},
{
"id": {
"extId": "113",
"year": "2001"
},
"Count": 446
},
{
"id": {
"extId": "115",
"year": "2000"
},
"Count": 742
}
];
var result=arr.reduce((result, current) => {
result.push({[current.id.year]: current.Count});
return result;
}, []);
console.log(result);
</script>

reduce will do the trick here for you:
var arr = [
{
"id": {
"extId": "112",
"year": "2000"
},
"Count": 1
},
{
"id": {
"extId": "113",
"year": "2001"
},
"Count": 446
},
{
"id": {
"extId": "115",
"year": "2000"
},
"Count": 742
},
{
"id": {
"extId": "116",
"year": "2001"
},
"Count": 44
}
];
let count = arr.reduce((acc, next) => {
acc[next.id.year] = (acc[next.id.year] || 0) + next.Count;
return acc;
}, {});
console.log(count);

ES6
You could use reduce() function to get required result.
DEMO
const data = [{"id": {"extId": "112","year": "2000"},"Count": 1},{"id": {"extId": "113","year": "2001"},"Count": 446},{"id": {"extId": "115","year": "2000"},"Count": 742}];
let result = data.reduce((r, {Count,id: {year}}) => {
r[year] = (r[year] || 0) + Count;
return r;
}, {});
console.log([result])
.as-console-wrapper {max-height: 100% !important;top: 0;}

var yearCount={};
var temp=[
{
"id": {
"extId": "112",
"year": "2000"
},
"Count": 1
},
{
"id": {
"extId": "113",
"year": "2001"
},
"Count": 446
},
{
"id": {
"extId": "115",
"year": "2000"
},
"Count": 742
}
];
temp.forEach(item=>{
var val=yearCount[item.id.year];
if (val){
yearCount[item.id.year]=val+item.Count;
}
else{
yearCount[item.id.year]=item.Count;
}
})
console.log(yearCount);

Related

How to group by and sum an array of objects javascript?

const array = [
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
}
]
var result = [];
array.reduce(function(res, value) {
if (!res['data']['toy'] || !res['data']['toy']['data']) {
res['data'] = {...value['data'] };
result.push(res['data'])
}
if (res['data']['available'] === value['data']['available'] && res['data']['toy']['id'] === value['data']['toy']['id']) {
res['data']['qty'] = parseInt(res['data']['qty']) + parseInt(value['data'].qty)
}
return res;
}, {'data': {}});
console.log(result)
I am working on a js project and I need a bit of help here. From the array, How to get a new array that has qty as the sum of the other qty value which data.toy.id and available same. i.e. I want the below array. My code is not working as excepted. Changes to the same or new code are also fine. Thank you.
const array = [
{
"data": {
"qty": "10",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
}
]
You group the array into an object, where the keys are concatenation of available and id properties and finally transform the object back to an array using Object.values.
const
array = [
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 10 }, available: "no" } },
{ data: { qty: "59", toy: { id: 10 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
],
result = Object.values(
array.reduce((r, { data }) => {
const k = data.available + data.toy.id;
if (r[k]) {
r[k].data.qty = String(Number(r[k].data.qty) + Number(data.qty));
} else {
r[k] = { data };
}
return r;
}, {})
);
console.log(result);
I'd suggest using Array.reduce() to group by a key, which will be combined value of the toy id and the available property.
We'd create a map of all toys based on this key, summing the quantity for each.
Finally, we'll use Object.values() to convert back into an array.
const array = [ { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 10, }, "available": "no" } }, { "data": { "qty": "59", "toy": { "id": 10, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } } ];
const result = Object.values(array.reduce((acc, { data: { qty, toy, available } }) => {
const key = `${toy.id}-${available}`;
acc[key] = acc[key] || { data: { qty: 0, toy, available } };
acc[key].data.qty += Number(qty);
return acc;
}, {}))
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
You can use Array#reduce() to create arrayHash object using as keys: ${c.data.toy.id}-${c.data.available}
Code:
const array = [{data: {qty: '5',toy: {id: 3,},available: 'yes',},},{data: {qty: '5',toy: {id: 10,},available: 'no',},},{data: {qty: '59',toy: {id: 10,},available: 'yes',},},{data: {qty: '5',toy: {id: 3,},available: 'yes',},},]
const arrayHash = array.reduce((a, { data }) => {
const key = `${data.toy.id}-${data.available}`
a[key] = a[key] || { data: { ...data, qty: 0 } }
a[key].data.qty = (+a[key].data.qty + +data.qty).toString();
return a
}, {})
const result = Object.values(arrayHash)
console.log(result)
I'd use just reduce
const a1 = [
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
}
]
const a2 = a1.reduce((acc, it) => {
let found = acc.find(
dp => dp.data.toy.id === it.data.toy.id && dp.data.available === it.data.available
)
if(found){
found.data.qty = ( Number(found.data.qty) + Number(it.data.qty) ).toString()
}
else acc.push(it)
return acc
}, [])
console.log(JSON.stringify(a2, null,2))

Object transformation using a functional approach

I am reading a simple data set from a data.txt file. I would like to take this data and transform it into a specific object as per my example below. I have managed to get it into a somewhat usable JSON object but this is not ideal. I have included an example of the desired object.
Here is my app.js file:
let output = fs.readFileSync('./data.txt', 'UTF8')
.trim()
.split('\r\n')
.map((line) => line.split(';'))
.reduce((customers, line) => {
customers.push({
name: line[0],
product: [{
item: line[1],
serial: line[2],
year: line[3]
}]
})
return customers
}, [])
console.log(JSON.stringify(output, null, 2))
This currently the above NodeJs code returns the following array object:
[
{
"name": "Nancy",
"product": [
{
"item": "Macbook Pro",
"serial": "A34D05980FCD4303",
"year": "2019"
}
]
},
{
"name": "Nancy",
"product": [
{
"item": "iPad",
"serial": "O0403X3028423C92",
"year": "2015"
}
]
},
{
"name": "Nancy",
"product": [
{
"item": "iPhone",
"serial": "X3830238S3309230",
"year": "2017"
}
]
},
{
"name": "John",
"product": [
{
"item": "Macbook Pro",
"serial": "X2020J393983H380",
"year": "2013"
}
]
},
{
"name": "John",
"product": [
{
"item": "iPhone",
"serial": "X38320093X032309",
"year": "2015"
}
]
},
{
"name": "fluffikins",
"product": [
{
"item": "iMac",
"serial": "F392D392033X3232",
"year": "2013"
}
]
},
{
"name": "fluffikins",
"product": [
{
"item": "iPad",
"serial": "FE322230D3223S21",
"year": "2011"
}
]
}
]
What I am trying to do is get the below object returned - ideally still following the same functional approach:
[
{
"name": "Nancy",
"product": [
{
"item": "Macbook Pro",
"serial": "A34D05980FCD4303",
"year": "2019"
},
{
"item": "iPad",
"serial": "O0403X3028423C92",
"year": "2015"
},
{
"item": "iPhone",
"serial": "X3830238S3309230",
"year": "2017"
}
]
},
{
"name": "John",
"product": [
{
"item": "Macbook Pro",
"serial": "X2020J393983H380",
"year": "2013"
},
{
"item": "iPhone",
"serial": "X38320093X032309",
"year": "2015"
}
]
},
{
"name": "fluffikins",
"product": [
{
"item": "iMac",
"serial": "F392D392033X3232",
"year": "2013"
},
{
"item": "iPad",
"serial": "FE322230D3223S21",
"year": "2011"
}
]
}
]
Here is my mock data set that lives in data.txt
Nancy;Macbook Pro;A34D05980FCD4303;2019
Nancy;iPad;O0403X3028423C92;2015
Nancy;iPhone;X3830238S3309230;2017
John;Macbook Pro;X2020J393983H380;2013
John;iPhone;X38320093X032309;2015
fluffikins;iMac;F392D392033X3232;2013
fluffikins;iPad;FE322230D3223S21;2011
Instead of an array you can use Map in reduce as accumulator, use name as key in Map and club value of all keys, finally just get the values Map to get desired output
const data = `Nancy;Macbook Pro;A34D05980FCD4303;2019
Nancy;iPad;O0403X3028423C92;2015
Nancy;iPhone;X3830238S3309230;2017
John;Macbook Pro;X2020J393983H380;2013
John;iPhone;X38320093X032309;2015
fluffikins;iMac;F392D392033X3232;2013
fluffikins;iPad;FE322230D3223S21;2011`
const final = data.split('\n')
.map(v => v.split(';'))
.reduce((op, [name, item, serial, year]) => {
let obj = { item, serial, year }
if (op.has(name)) {
op.get(name).products.push(obj)
} else{
op.set(name,{name, products:[obj]})
}
return op
}, new Map())
console.log([...final.values()])
Here is a "functional version" that utilizes a Map to find duplicates in O(1):
(map => (
fs.readFileSync('./data.txt', 'UTF8')
.trim()
.split('\r\n')
.map((line) => line.split(';'))
.forEach(([name, item, serial, year]) =>
map.has(name)
? map.get(name).product.push({ item, serial, year })
: map.set(name, { name, product: [{ item, serial, year }] })
),
[...map.values()]
)(new Map)
But seriously, whats so bad about imperative style?:
const customers = new Map;
const entries = fs.readFileSync('./data.txt', 'UTF8')
.trim()
.split('\r\n');
for(const entry of entries) {
const [name, item, serial, year] = entry.split(";");
const product = { item, serial, year };
if(customers.has(name)) {
customers.get(name).product.push(product);
} else customers.set(name, { name, product: [product] });
}
const result = [...customers.values()];
You can modify the .reduce function to only add a new item to the array if there isn't one with that name. If there is, just add the product to that item's product array.
const data = `Nancy;Macbook Pro;A34D05980FCD4303;2019
Nancy;iPad;O0403X3028423C92;2015
Nancy;iPhone;X3830238S3309230;2017
John;Macbook Pro;X2020J393983H380;2013
John;iPhone;X38320093X032309;2015
fluffikins;iMac;F392D392033X3232;2013
fluffikins;iPad;FE322230D3223S21;2011`;
const result = data.trim()
.split('\n')
.map((line) => line.split(';'))
.reduce((customers, line) => {
const product = {
item: line[1],
serial: line[2],
year: line[3]
};
const customer = customers.find(({
name
}) => name === line[0]);
if (customer) {
customer.product.push(product);
} else {
customers.push({
name: line[0],
product: [product]
});
}
return customers
}, []);
console.log(result);

What is the most performant way to convert an Array of Object to an Object with unique keys

I am trying to figure out the most performant Javascript way to convert an array of objects, into an object with unique keys and an array full of objects as the value.
For Example:
const array = [
{ "name": "greg", "year": "2000" },
{ "name": "john", "year": "2002" },
{ "name": "bob", "year": "2005" },
{ "name": "ned", "year": "2000" },
{ "name": "pam", "year": "2000" },
];
I would like this converted to:
{
"2000": [
{ "name": "greg", "year": "2000" },
{ "name": "ned", "year": "2000" },
{ "name": "pam", "year": "2000" }
],
"2002": [ { "name": "john", "year": "2002" } ],
"2005": [ { "name": "bob", "year": "2005" } ],
}
As of now, this is what I've done so far:
let yearsObj = {};
for (let i=0; i<array.length; i++) {
if (!yearsObj[array[i].year]) {
yearsObj[array[i].year] = [];
}
yearsObj[array[i].year].push(array[i]);
}
you can use a more elegant way to do it by using array's reduce function
// # impl
const group = key => array =>
array.reduce(
(objectsByKeyValue, obj) => ({
...objectsByKeyValue,
[obj[key]]: (objectsByKeyValue[obj[key]] || []).concat(obj)
}),
{}
);
// # usage
console.log(
JSON.stringify({
byYear: group(array),
}, null, 1)
);
// output
VM278:1 {
"carsByBrand": {
"2000": [
{
"name": "greg",
"year": "2000"
},
{
"name": "ned",
"year": "2000"
},
{
"name": "pam",
"year": "2000"
}
],
"2002": [
{
"name": "john",
"year": "2002"
}
],
"2005": [
{
"name": "bob",
"year": "2005"
}
]
}
}
It could be as simple as that Object.fromEntries(array.map(obj => [obj.year,obj])) even it is not exactly what you need, but talking about performance it is way slower than all proposed, so i'm giving it as an bad example of showing how the short statement is not always the fastest.
Your way seems to be the fastest taking about performance.
Run the snippet below to see the actual timing.
// common
let array = [
{ "name": "greg", "year": "2000" },
{ "name": "john", "year": "2002" },
{ "name": "bob", "year": "2005" },
{ "name": "ned", "year": "2000" },
{ "name": "pam", "year": "2000" },
];
// simple as a statement way
console.time();
console.log(Object.fromEntries(array.map(obj => [obj.year,obj])));
console.timeEnd();
// using .reduce way
console.time();
const result = array.reduce((prev, curr) => {
const { year } = curr;
if (prev[year]) {
prev[year].push(curr);
} else {
prev[year] = [curr];
}
return prev;
}, {});
console.log(result);
console.timeEnd();
// your way
console.time();
let yearsObj = {};
for (let i=0; i<array.length; i++) {
if (!yearsObj[array[i].year]) {
yearsObj[array[i].year] = [];
}
yearsObj[array[i].year].push(array[i]);
}
console.log(yearsObj);
console.timeEnd();
A for loop (imperative style) like you have is likely to be the fastest in most situations. However, in this case you are not likely to see much of a difference. One thing you could do to improve the code in your example is to get the array length before the for loop and assign it to the variable, so that it's not calculated every iteration of the loop.
const yearsObj = {};
const arrayLength = array.length; // Only calculate array length once
for (let i=0; i<arrayLength; i++) {
if (!yearsObj[array[i].year]) {
yearsObj[array[i].year] = [];
}
yearsObj[array[i].year].push(array[i]);
}
In this situation, my preference would be to use Array.reduce(). It is more readable and the performance difference will be negligible.
const arr = [
{ name: 'greg', year: '2000' },
{ name: 'john', year: '2002' },
{ name: 'bob', year: '2005' },
{ name: 'ned', year: '2000' },
{ name: 'pam', year: '2000' },
];
const result = arr.reduce((prev, curr) => {
const { year } = curr;
if (prev[year]) {
prev[year].push(curr);
} else {
prev[year] = [curr];
}
return prev;
}, {});
/* Result:
{ '2000':
[ { name: 'greg', year: '2000' },
{ name: 'ned', year: '2000' },
{ name: 'pam', year: '2000' } ],
'2002': [ { name: 'john', year: '2002' } ],
'2005': [ { name: 'bob', year: '2005' } ] }
*/

Grouping array of objects by multiple keys

I feel embarrassed for asking this question as I should know how to figure it out, but I'm spinning my wheels on grouping an array of objects by multiple keys.
Here's the data:
[
{
"car": "audi",
"type": "A6",
"style": "Avant",
"year": "1996"
},
{
"car": "audi",
"type": "A4",
"style": "2",
"year": "2006"
},
{
"car": "audi",
"type": "A4",
"style": "L W12",
"year": "2006"
},
{
"car": "audi",
"type": "80",
"style": "GLE",
"year": "1975"
},
{
"car": "audi",
"type": "A6",
"style": "Avant L",
"year": "1996"
},
{
"car": "audi",
"type": "A6",
"style": "3.2 Multitronic",
"year": "2006"
},
]
What I've been trying to generate with little success is the following:
[{
"audi": [{
"1996": {
"A6": ["Avant, Avant L"]
}
}, {
"2006": }
"A6": ["3.2 Multitronic"],
"A4": ["L W12", "2"]
}
}
....
}]
The schema is:
{
"car1": [{
"year1": {
"style1": ["trim1", "trim2"],
"style2": ["trim1", "trim2"]
},
"year1": {
"style1": ["trim1", "trim2"],
"style2": ["trim1", "trim2"]
}
}],
"car2": [{
"year1": {
"style1": ["trim1", "trim2"],
"style2": ["trim1", "trim2"]
},
"year2": {
"style1": ["trim1", "trim2"],
"style2": ["trim1", "trim2"]
}
}]
}
I've tried the following with lodash
let result = _.chain(carData)
.groupBy('car')
.toPairs()
.map(function(curr) {
return _.zipObject(['car', 'year'], curr);
})
.value();
This gets me part of the way, but I end up with incomplete data when it comes to the styles and types for each year of the car.
You could use a hash object and a nested approach for the given properties.
var data = [{ car: "audi", type: "A6", style: "Avant", year: 1996 }, { car: "audi", type: "A4", style: 2, year: 2006 }, { car: "audi", type: "A4", style: "L W12", year: 2006 }, { car: "audi", type: 80, style: "GLE", year: 1975 }, { car: "audi", type: "A6", style: "Avant L", year: 1996 }, { car: "audi", type: "A6", style: "3.2 Multitronic", year: 2006 }],
keys = ['car', 'year', 'type'],
result = [];
data.forEach(function (a) {
keys.reduce(function (r, k) {
var o = {};
if (!r[a[k]]) {
r[a[k]] = { _: [] };
o[a[k]] = r[a[k]]._;
r._.push(o);
}
return r[a[k]];
}, this)._.push(a.style);
}, { _: result });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's a (slightly verbose) solution that generates exactly the JSON object shape you wanted and groups by unlimited keys:
var cars = [{
"car": "audi",
"type": "A6",
"style": "Avant",
"year": "1996"
}, {
"car": "audi",
"type": "A4",
"style": "2",
"year": "2006"
}, {
"car": "audi",
"type": "A4",
"style": "L W12",
"year": "2006"
}, {
"car": "audi",
"type": "80",
"style": "GLE",
"year": "1975"
}, {
"car": "audi",
"type": "A6",
"style": "Avant L",
"year": "1996"
}, {
"car": "audi",
"type": "A6",
"style": "3.2 Multitronic",
"year": "2006"
}, ];
function groupBy(list, prop) {
return list.reduce((groupped, item) => {
var key = item[prop];
delete item[prop];
if (groupped.hasOwnProperty(key)) {
groupped[key].push(item);
} else {
groupped[key] = [item];
}
return groupped
}, {});
}
function groupSubKeys(obj, properties, propIndex) {
var grouppedObj = groupBy(obj, properties[propIndex]);
Object.keys(grouppedObj).forEach((key) => {
if (propIndex < properties.length - 2) {
grouppedObj[key] = groupSubKeys(grouppedObj[key], properties, propIndex + 1);
} else {
grouppedObj[key] = grouppedObj[key].map(item => item[properties[propIndex + 1]])
}
});
return grouppedObj;
}
function groupByProperties(list, properties) {
return groupSubKeys(list, properties, 0);
}
console.log(groupByProperties(cars, ['car', 'year', 'type', 'style']));
Here's a running example:
http://codepen.io/rarmatei/pen/evmBOo
const groupBy = function groupBy(list, properties, propertyIndex) {
// current property index
let i = propertyIndex === undefined ? 0 : propertyIndex;
// group by
let grouppedObj = list.reduce((acc, obj) => {
let groupedValue = obj[properties[i]];
if (!groupedValue) {
return acc;
}
if (!acc[groupedValue]) {
acc[groupedValue] = [];
}
acc[groupedValue].push({ ...obj, groupBy: properties.join(",") });
return acc;
}, {});
// group by nested
const keys = Object.keys(grouppedObj);
if (i === properties.length - 1) {
return grouppedObj;
}
keys.forEach((key) => {
grouppedObj[key] = groupBy(grouppedObj[key], properties, i + 1);
});
return grouppedObj;
};
const data =[
{
"year": "2021",
"cabin": "1",
"months": ["1", "2"]
},
{
"year": "2021",
"cabin": "1",
"months": ["4"]
},
{
"year": "2021",
"cabin": "2",
"months": ["1", "2"]
},
{
"year": "2022",
"cabin": "1",
"months": ["1", "2"]
},
{
"year": "2022",
"cabin": "1",
"months": ["4"]
},
{
"year": "2022",
"cabin": "2",
"months": ["1", "2"]
}
];
const results=groupBy(data, ["year", "cabin"]);
console.log(results);

Converting javascript object to ordered comma separated value

I am trying to get the items in the json arranged in an orderly manner. I was able to select the "term" values present in the json, but is it possible to arrange this in the manner I have shown in the expected output part? I have added a jsfiddle link to show where I have reached:
[
{
"Link": "http://testLink.com/1",
"_index": "test",
"_source": {
"Author": "SAM",
"Map": [
{
"Company": [
{
"Apple_Inc": [
{
"count": 1,
"term": "Apple"
}
],
"sector": "Technology",
"term": "Apple Inc",
"ticker": "AAPL",
"type": "BCap"
}
],
"count": 1,
"term": "Company"
},
{
"Country": [
{
"Canada": [
{
"Canada": [
{
"count": 1,
"term": "Toronto"
}
],
"count": 1,
"term": "Canada"
}
],
"United_States": [
{
"count": 1,
"term": "United States"
}
],
"currency": "Dollar (USD)",
"index": "DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX",
"region": "North Americas",
"term": "Canada"
}
],
"count": 1,
"term": "Country"
},
{
"Personality": [
{
"count": 1,
"term": "Bart Prince"
},
{
"count": 1,
"term": "Thomas"
},
{
"count": 1,
"term": "Deborah Hornstra"
},
{
"count": 1,
"term": "Henderson Sotheby"
},
{
"count": 1,
"term": "Max Alliance"
}
],
"count": 5,
"term": "Personality"
}
]
},
"id": "YMFT112"
},
{
"Link": "http://testLink.com/2",
"_id": "YMFT113",
"_index": "test",
"_source": {
"Author": "MAX",
"Map": [
{
"Company": [
{
"Microsoft Corp": [
{
"count": 1,
"term": "Microsoft"
}
],
"sector": "Technology",
"term": "Microsoft",
"ticker": "AAPL",
"type": "BCap"
}
],
"count": 1,
"term": "Company"
},
{
"Country": [
{
"Brazil": [
{
"count": 1,
"term": "Brazil"
}
],
"currency": "Dollar (USD)",
"region": "South Americas",
"term": "Brazil"
}
],
"count": 1,
"term": "Country"
},
{
"SalesRelated": [
{
"count": 1,
"term": "traffic"
}
]
},
{
"Personality": [
{
"count": 1,
"term": "Maximor"
},
{
"count": 1,
"term": "R.V.P"
},
{
"count": 1,
"term": "Wenger"
},
{
"count": 1,
"term": "SAF"
}
],
"count": 4,
"term": "Personality"
}
]
}
}
]
http://jsbin.com/exuwet/3/edit
Prompt Input
If field Selected = Country,
Expected Output:
YMFT112; Country; United States; United States; NA; http://testLink.com/1;
YMFT112; Country; Canada; Canada; Toronto; http://testLink.com/1;
YMFT113; Country; Brazil; Brazil; NA; http://testLink.com/2;
If field Selected = Company,
Expected Output:
YMFT112; Company; Apple Inc; Apple; http://testLink.com/1;
YMFT113; Company; Microsoft Corp; Microsoft; http://testLink.com/2;
You can use the JSON object when natively available or use JSON2 as a shim.
After that it's just a matter of using JavaScript's built in sorting capability. You supply a function that compares to array items against each other
var myArray = JSON.parse(jsonString);
myArray.sort(function(a, b){
var nameA = a._source.Map.Company.term;
var nameB = b._source.Map.Company.term;
if (nameA === nameB) {
return 0;
} else if (nameA < nameB) {
return -1
}
return 1;
});
With eval('(' + json_object + ')'), you will be able to create a JavaScript Object. This object will be an array, and you can acess the properties using ..
For example, if your json_object is called data, for example:
Then
var temp = eval('(' + data + ')'); // temp now is an array.
if you want to access the first _index or id from the json object:
"_index": "test",
"id": "YMFT112",
do alert(temp[0]._index), and it will show you "test". For the other properties, follow the same logic. This stackoverflow question, or the JSON page will help you understand what you have to do in other to have your task accomplished. Yahoo has an API called YUI which may be even more helpful.
Here is a solution using object-scan
// const objectScan = require('object-scan');
const data = [{"_index":"test","id":"YMFT112","_source":{"Author":"SAM","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Apple_Inc":[{"count":1,"term":"Apple"}],"term":"Apple Inc","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"North Americas","index":"DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX","United_States":[{"count":1,"term":"United States"}],"term":"Canada","currency":"Dollar (USD)","Canada":[{"count":1,"term":"Canada","Canada":[{"count":1,"term":"Toronto"}]}]}]},{"count":5,"term":"Personality","Personality":[{"count":1,"term":"Bart Prince"},{"count":1,"term":"Thomas"},{"count":1,"term":"Deborah Hornstra"},{"count":1,"term":"Henderson Sotheby"},{"count":1,"term":"Max Alliance"}]}]},"Link":"http://testLink.com/1"},{"_index":"test","_id":"YMFT113","_source":{"Author":"MAX","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Microsoft Corp":[{"count":1,"term":"Microsoft"}],"term":"Microsoft","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"South Americas","Brazil":[{"count":1,"term":"Brazil"}],"term":"Brazil","currency":"Dollar (USD)"}]},{"SalesRelated":[{"count":1,"term":"traffic"}]},{"count":4,"term":"Personality","Personality":[{"count":1,"term":"Maximor"},{"count":1,"term":"R.V.P"},{"count":1,"term":"Wenger"},{"count":1,"term":"SAF"}]}]},"Link":"http://testLink.com/2"}];
const find = (term, input) => {
const r = objectScan([`[*]._source.Map[*].${term}[*].**.term`], {
reverse: false,
filterFn: ({ key, parents, context }) => {
if (Object.values(parents[0]).some((e) => e instanceof Object)) {
return;
}
const root = parents[parents.length - 2];
context.push([
root.id || root._id,
parents[parents.length - 5].term,
key[key.length - 3].replace(/_/g, ' '),
...parents.slice(0, -7).filter((e) => !Array.isArray(e)).map((p) => p.term).reverse(),
root.Link
]);
}
})(input, []);
const maxLength = Math.max(...r.map((e) => e.length));
r
.filter((e) => e.length < maxLength)
.forEach((e) => e.splice(-1, 0, 'NA'.repeat(maxLength - e.length)));
return r;
};
console.log(find('Country', data).map((e) => e.join('; ')).join('\n'));
/* =>
YMFT112; Country; United States; United States; NA; http://testLink.com/1
YMFT112; Country; Canada; Canada; Toronto; http://testLink.com/1
YMFT113; Country; Brazil; Brazil; NA; http://testLink.com/2
*/
console.log(find('Company', data).map((e) => e.join('; ')).join('\n'));
/* =>
YMFT112; Company; Apple Inc; Apple; http://testLink.com/1
YMFT113; Company; Microsoft Corp; Microsoft; http://testLink.com/2
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Categories