Javascript Creating Array in a for loop - javascript

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>

Related

How to convert a specified JSON object value to an array

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);

How to compare array and object in Javascript?

I have two json array and object
I would like to compare two json and push another object
obj1 = ["user1", "user2"]
obj2 = [
{
"userName": "user1",
"id": "14"
},
{
"userName": "user2",
"id": "9",
},
{
"userName": "user3",
"id": "3",
},
{
"userName": "user4",
"id": "1",
}
]
I would like to get the result as below
[
{
"userName": "user1",
"id": "14"
},
{
"userName": "user2",
"id": "9",
}
]
After, I tried to compare two arrays and get a result what I need.
var obj1 = ["user1","user2"]
var obj2 = [
{
"userName": "user1",
"id": "14"
},
{
"userName": "user2",
"id": "9",
},
{
"userName": "user3",
"id": "3",
},
{
"userName": "user4",
"id": "1",
}
]
var objArray = [];
for (var i = 0; i < obj.length; i++) {
if (obj1[i] === obj2.userName) {
objArray.push(obj2[i]);
}
return objArray;
Please help me to solve the issue.
Thanks in advance
You could filter by checking the name with Array#includes.
var array1 = ["user1", "user2"],
array2 = [{ userName: "user1", id: "14" }, { userName: "user2", id: "9", }, { userName: "user3", id: "3", }, { userName: "user4", id: "1", }],
result = array2.filter(({ userName }) => array1.includes(userName));
console.log(result);
You need two loops:
iterate through obj1[i], and for each index of obj1...
iterate through obj2[] and test each object to see whether the username property's value equals that of obj[i].
var obj1 = ["user1","user2"]
var obj2 = [
{
"userName": "user1",
"id": "14"
},
{
"userName": "user2",
"id": "9",
},
{
"userName": "user3",
"id": "3",
},
{
"userName": "user4",
"id": "1",
}]
function myFunction(){
var objArray = [];
for (var i=0; i < obj1.length; i++) {
for (var userIndex=0; userIndex < obj2.length; userIndex++){
if (obj1[i] === obj2[userIndex].userName){
objArray.push( obj2[userIndex] );
}
}
}
return objArray;
};
console.log(myFunction());

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?

Jquery : transform nested json object to another json object

In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)

Categories

Resources