How to convert a specified JSON object value to an array - javascript

So imagine having a JSON file like:
[
{ "name": "David", "code": "DA" },
{ "name": "Solomon", "code": "SO" },
{ "name": "Mirage", "code": "MI" }
]
How can I convert it to something like this:
['David', 'Solomon', 'Mirage']and
['DA', 'SO', 'MI]

let data = [
{ "name": "David", "code": "DA" },
{ "name": "Solomon", "code": "SO" },
{ "name": "Mirage", "code": "MI" }
];
const result = data.map(item => item.name);
const result2 = data.map(item => item.code);
console.log(result, result2);

let data = [
{ "name": "David", "code": "DA" },
{ "name": "Solomon", "code": "SO" },
{ "name": "Mirage", "code": "MI" }
];
let a1= [];
let a2= [];
data.forEach(ei =>{
a1.push(ei.name);
a2.push(ei.code);
})
console.log(a1);
console.log(a2);

Related

How to filter children JSON objects based on some value Angular 8

I am getting API response inside filterchildrenByRegion() function,
I want to remove those object which are not matching with the selected Region and return all data as it is.
Ex 1 - If i will pass '1UL Africa' inside changeRegion() function,than it will return data as my expected output 1.
Ex - 2 - If i will pass 'South Africa"' inside changeRegion() function,than it will return data as my expected output 2.
changeRegion(){
this.newRegion = this.filterchildrenByRegion('1UL Africa');
}
filterchildrenByRegion(region){
this.data = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
return this.data.filter(x => x.children.map(child => child.region).includes(regionName));
};
Expected Output 1
result = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
}
]
}
];
I tried below code but it is returning empty result to me
getClusterObjectByRegion(regionName: string) {
this.data = this.clusterFactoryList;
return this.data.map((x) => {
const childrenFulfillingTheSearch = x.children.filter(c => c.buSubRegion.includes(regionName));
if (childrenFulfillingTheSearch.length === 0) {
return undefined;
}
return {
...x,
children: childrenFulfillingTheSearch
};
}).filter(x => x !== undefined);
};
Expected Output 2
result = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
}
]
}
];
Maybe not the most efficient, but it works, if I understood your needs correctly:
function getByRegion(region: string) {
return data.map(r => ({...r, children: r.children.filter(c => c.region === region)}))
.filter(r => r.children.length > 0);
}

Javascript Creating Array in a for loop

I have an json array in format as below.
{
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"fields": [{
"name": "workphone",
"values": {
"answer": "8888888888"
}
}, {
"name": "Industry",
"values": {
"answer": "computer"
}
}]
},
{
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"fields": [{
"name": "workphone",
"values": {
"answer": "9999999999"
}
},
{
"name": "market",
"values": {
"answer": "Outer"
}
}
]
}
]
}
I want to convert it to a simpler array like below, so it will be easier to search :
{
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"workphone": "8888888888",
"Industry": "computer"
}, {
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"workphone": "9999999999",
"market": "Outer"
}]
}
I wrote the code as below , but I am getting error as
TypeError: Cannot set property 'id' of undefined
Here is the code:
let temp = response.data.agents;
let temparray=[];
for(let i = 0; i < temp.length; i++) {
let agent = temp[i];
Object.keys(agent).forEach(function(key) {
if(key=='fields'){
let tempfield = agent.fields;
for(let j = 0; j < tempfield.length; j++) {
let ccs = tempfield[j];
Object.keys(ccs).forEach(function(keys) {
if(keys=='name'){
temparray[i][ccs.name] = ccs.values.answer;
}
});
}
}
else{
temparray[i][key] = agent[key];
});
}
Here's a map and reduce approach using object destructuring to split out the fields in order to reduce then to a flattened object that can be merged with the other properties
data.agents = data.agents.map(({fields, ...rest}) => {
fields = fields.reduce((a,{name:n,values:v}) => (a[n] = v.answer, a),{});
return {...rest, ...fields};
});
console.log(data)
<script>
let data = {
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"fields": [{
"name": "workphone",
"values": {
"answer": "8888888888"
}
}, {
"name": "Industry",
"values": {
"answer": "computer"
}
}]
},
{
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"fields": [{
"name": "workphone",
"values": {
"answer": "9999999999"
}
},
{
"name": "market",
"values": {
"answer": "Outer"
}
}
]
}
]
}
</script>
Can you try Initializing temparray[i] as object
let tesp = [{"agents":[ {"id":"1",
"first_name":"Stacy",
"last_name":"Thompson",
"fields":[ {"name":"workphone", "values": {"answer":"8888888888"}}, {"name":"Industry", "values": {"answer":"computer"}}]
}, {"id":"2",
"first_name":"Jhon",
"last_name":"Deo",
"fields":[ {"name":"workphone", "values": {"answer":"9999999999"}}, {"name":"market", "values": {"answer":"Outer"}}
]
}
]}];
let temp = tesp;
let temparray = [];
for (let i = 0; i < temp.length; i++) {
let agent = temp[i];
Object.keys(agent).forEach(function (key) {
if (key == 'fields') {
let tempfield = agent.fields;
for (let j = 0; j < tempfield.length; j++) {
let ccs = tempfield[j];
Object.keys(ccs).forEach(function (keys) {
if (keys == 'name') {
temparray[i][ccs.name] = ccs.pivot.answer;
}
});
}
}
else {
temparray[i] = {};
temparray[i][key] = agent[key];
}
});
console.log(temparray);
}
const newData = data.agents.map((agent) => {
const { first_name, last_name, fields } = agent;
return {
first_name,
last_name,
workphone: fields[0].values.answer,
market: fields[1].values.answer,
}
});
console.log(newData);
Used map to iterate over agents. As map returns a new array, I returned the individual object inside .map
Or you can use the above answer, charlietfl's. If you have dynamic fields.
function convert() {
let asArray = Object.values( input )[0];
for( let i in asArray) {
for( let j in asArray[i].fields ) {
asArray[i][asArray[i].fields[j].name] = Object.values(asArray[i].fields[j].values).join(',');
}
delete asArray[i].fields;
}
// console.log(asArray);
return {'agents': asArray};
}
var input = {
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"fields": [{
"name": "workphone",
"values": {
"answer": "8888888888"
}
}, {
"name": "Industry",
"values": {
"answer": "computer"
}
}]
},
{
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"fields": [{
"name": "workphone",
"values": {
"answer": "9999999999"
}
},
{
"name": "market",
"values": {
"answer": "Outer"
}
}
]
}
]
};
console.log( convert( input ) );
Desired output:
<pre style="height: 200px; overflow: scroll;">
{
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"workphone": "8888888888",
"Industry": "computer"
}, {
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"workphone": "9999999999",
"market": "Outer"
}]
}
</pre>

Create new javascript object from 2 JSON objects grouped by id

I have below dynamic nested JSON object arrays and I wanted to get the desired output with JavaScript grouped by id from both.
First Array:
[
{
"id": "11",
"name": "emp1",
"location": [
{ "name": "abc", "id": "lc1" }
]
},
{
"id": "11",
"name": "emp2",
"location": [
{ "name": "abc", "id": "lc1" },
]
},
{
"id": "22",
"name": "emp3",
"location": [
{ "name": "xyz", "id": "lc2" }
]
}
]
Second array like below.
[
{
"name": "sub1",
"id": "11"
...
},
{
"name": "sub1.1",
"id": "11"
...
},
{
"name": "sub2",
"id": "22"
...
}
]
Desired Output:
[
{
"id": "11",
"first": [{"name": "emp1"},
{"name": "emp2"}],
"second": [{"name": "sub1"},{"name": "sub1.1"}],
"location": [{"name": "abc"}]
},
{
"id": "22",
"first": [{"name": "emp3"}],
"second": [{"name": "sub2"}],
"location": [{"name": "xyz"}]
}
]
How to get the desired output like above using javascript/angularjs?
I would do it using the amazing Array#reduce function.
Note that I have named your first array as a1, second as a2 and result as res.
a1.reduce(function(arr, obj) {
var existing = arr.filter(function(res) {
return res.id === obj.id
})[0]
if (existing) {
existing.first.push({
name: obj.name
})
} else {
var second = a2.filter(function(res) {
return res.id === obj.id
})
var secondObj = second.length ? second.map(function(sec) {
return {
name: sec.name
};
}) : []
arr.push({
id: obj.id,
first: [{
name: obj.name
}],
second: secondObj,
location: obj.location
})
}
return arr;
}, [])
Here's the working snippet. Take a look!
var a1 = [{
"id": "11",
"name": "emp1",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "11",
"name": "emp2",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "22",
"name": "emp3",
"location": [{
"name": "xyz",
"id": "lc2"
}]
}
]
var a2 = [{
"name": "sub1",
"id": "11"
}, {
"name": "sub1.1",
"id": "11"
},
{
"name": "sub2",
"id": "22"
}
]
var res = a1.reduce(function(arr, obj) {
var existing = arr.filter(function(res) {
return res.id === obj.id
})[0]
if (existing) {
existing.first.push({
name: obj.name
})
} else {
var second = a2.filter(function(res) {
return res.id === obj.id
})
var secondObj = second.length ? second.map(function(sec) {
return {
name: sec.name
};
}) : []
arr.push({
id: obj.id,
first: [{
name: obj.name
}],
second: secondObj,
location: obj.location
})
}
return arr;
}, [])
console.log(res)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
var red1 = [{
"id": "11",
"name": "emp1",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "11",
"name": "emp2",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "22",
"name": "emp3",
"location": [{
"name": "xyz",
"id": "lc2"
}]
}
]
var b = [{
"name": "sub1",
"id": "11"
},
{
"name": "sub2",
"id": "22"
}
]
var identication = {}
var result = []
red1.forEach(function(val) {
if (val['id'] in identication) {
var t = {}
t['name'] = val['name']
result[identication[val['id']]]['first'].push(t)
} else {
var t = {}
t['name'] = val['name']
val['first'] = []
val['first'].push(t)
delete val['name']
var identity = result.push(val)
identication[val['id']] = identity - 1;
}
})
b.forEach(function(d) {
if (d['id'] in identication) {
var t = {
'name': d['name']
}
if (!('second' in result[identication[d['id']]])) {
result[identication[d['id']]]['second'] = []
}
result[identication[d['id']]]['second'].push(t)
} else {
var t = {}
for (key in d) {
if (key == 'name')
continue
t[key] = d[key]
}
t['second'] = [{
'name': d['name']
}]
var identity = result.push(t)
identication[d['id']] = identity - 1;
}
})
console.log(result)

Replace js code with aggregate in mongodb

I have mongo document called groups. This is array of students and subjects.
Each subject has an array of lessons.
Each lesson has an array of marks.
Generally, document looks like this:
[
{
"students": [
{ "_id": "0", "firstName": "Bob", "lastName": "Jhonson" },
{ "_id": "1", "firstName": "Jackie", "lastName": "Chan" }
// other students ...
],
"subjects": [
{
"name": "Algebra",
"lessons": [
{
"date": 1489363200,
"marks": [
{ "student_id": "0", "value": 5 },
{ "student_id": "1", "value": 4 }
// other marks...
]
}, {
"date": 1489622400,
"marks": [
{ "student_id": "0", "value": 3 },
{ "student_id": "1", "value": 2 }
// other marks...
]
}
// other lessons...
]
}
]
}
]
Then I use js function to transform this data to something like this:
[
{
"_id": "5a89ca11abc4ffd25a430420",
"subjects": [
{
"name": "Algebra",
"dates": [1489363200, 1489622400],
"students": [
{
"_id": "0",
"firstName": "Bob",
"lastName": "Jhonson",
"marks": [ 5, 3 ]
},
{
"_id": "1",
"firstName": "Jackie",
"lastName": "Chan",
"marks": [ 4, 2 ]
}
]
}
]
}
]
Function which transforms json document:
function transformData (groups) { // groups - array
let newGroups = [];
for (let group of groups) {
newGroup = {};
for (let key in group) {
if (key === 'students' || key === 'subjects') continue;
newGroup[key] = group[key];
}
newGroup.subjects = [];
for (let subject of group.subjects) {
let newSubject = {
name: subject.name,
dates: [],
students: []
};
for (let student of group.students) {
let index = newSubject.students.push(student) - 1;
newSubject.students[index].marks = [];
}
for (let lesson of subject.lessons) {
let index = newSubject.dates.push(lesson.date) - 1;
for (let mark of lesson.marks) {
for (let student of newSubject.students) {
if (student._id !== mark.student_id) continue;
while(student.marks.length !== index) {
student.marks.push(null);
}
student.marks.push(mark.value);
}
}
}
newGroup.subjects.push(newSubject);
}
newGroups.push(newGroup);
}
return newGroups;
}
How can I replace this function with mongodb aggregation?

Building new JSON from existing one

I want to build an new JSON from existing one. The source has sections and rubrics that I no longer need for a listing. The new object called 'items' should have an array of the items.
The final JSON should be sorted by attribute 'name' and look like
{
"items": [
{
"id": 10000006,
"name": "Boah"
},
{
"id": 10000013,
"name": "Gut"
},
{
"id": 10000003,
"name": "Ipsum"
},
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000002,
"name": "Stet"
}
]
}
For building the new JSON I get this source:
{
"sections": [
{
"name": "FooBar",
"rubrics": [
{
"name": "Foo",
"items": [
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000002,
"name": "Stet"
},
{
"id": 10000003,
"name": "Ipsum"
}
]
},
{
"name": "Bar",
"items": [
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000006,
"name": "Boah"
}
]
}
]
},
{
"name": "BlahBloob",
"rubrics": [
{
"name": "Bla",
"items": [
{
"id": 10000013,
"name": "Gut"
}
]
},
{
"name": "Bloob",
"items": [
{
"id": 10000014,
"name": "Name"
},
{
"id": 10000015,
"name": "Lorem"
}
]
}
]
}
]
}
What do you think? How can I do this with plain JavaScript or maybe TypeScript?
Thanks for reading and have time for my question. And thanks for reply in advance.
Here you go. You just need to iterate over each rubric of each section of your source to get the items. At the end, sort your list of items by items, and you're done.
This example uses ES6 syntax, but it's easy to convert it to ES5 if needed.
function extractItems(source) {
const items = [];
for (const section of source.sections) {
for (const rubric of section.rubrics) {
items.push(...rubric.items);
}
}
items.sort((a, b) => a.name.localeCompare(b.name));
return { items };
}
A more functional approach use map and reduce to pick the rubrics and merge them.
data.sections
.map(section => section.rubrics) // get rubrics
.reduce((a, b) => a.concat(b)) // merge rubrics
.map(rubric => rubric.items) // get items from each rubric
.reduce((a, b) => a.concat(b)) // merge items
.sort((a, b) => a.name.localeCompare(b.name)); // sort
function(oldObj) {
var newObj = {
"items": []
};
oldObj.sections.forEach(function(section) {
section.rubrics.forEach(function(rubric) {
rubric.items.forEach(function(item) {
newObj.items.push(item);
});
});
});
newObj.items = newObj.items.sort(function(a, b) {
if (a.name < b.name) { return -1; }
if (a.name > b.name) { return 1; }
return 0;
});
return newObj;
}
And simply use JSON.parse() and JSON.stringify() to convert JSON to and from objects.
It might help you
var data ={
"sections": [
{
"name": "FooBar",
"rubrics": [{"name": "Foo", "items": [{"id": 10000001,"name": "Lorem"}, {"id": 10000002,"name": "Stet"}, {"id": 10000003,"name": "Ipsum"}]
}, {
"name": "Bar",
"items": [{
"id": 10000004,
"name": "Name"
}, {
"id": 10000005,
"name": "Lorum"
}, {
"id": 10000006,
"name": "Boah"
}]
}]
}, {
"name": "BlahBloob",
"rubrics": [{
"name": "Bla",
"items": [{
"id": 10000013,
"name": "Gut"
}]
}, {
"name": "Bloob",
"items": [{
"id": 10000014,
"name": "Name"
}, {
"id": 10000015,
"name": "Lorem"
}]
}]
}]
};
var itemObj = {};
var itemArr = [];
var sections = data.sections;
for(var i=0;i<sections.length;i++)
{
for(var j=0;j<sections[i].rubrics.length;j++){
for(var k=0;k<sections[i].rubrics[j].items.length;k++){
var itemObj;
itemObj['id'] = sections[i].rubrics[j].items[k].id;
itemObj['name'] = sections[i].rubrics[j].items[k].name;
itemArr.push(itemObj);
}
}
}
var finalObj = {"items":itemArr};
console.log(finalObj);
JSFiddle

Categories

Resources