parse nested javascript array - javascript

I have this array
air_content: '',
compaction_method: 1,
concrete_cylinders: [
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
}
]
I'm trying to parse them when i post the data ( formik modifies them back to text so i am required to parse them as int for my backend )
My post looks like this ( this works except for the nested objects i want them parsed as integer also )
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders
});
the psuedo/My best try of the code of what I'm trying to do is the below
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders: {
[concrete_cylinders.id]: parseInt(concrete_cylinders.id),
[concrete_cylinders.curing]: parseInt(concrete_cylinders.curing)
}
});
Thankyou for assistance

before calling axios.post you'll need to
concrete_cylinders.forEach(x => {
x.id = parseInt(x.id);
x.curing = parseInt(c.curing);
});
or, if you really want, you can do it like
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders: concrete_cylinders.map(x => {
x.id = parseInt(x.id);
x.curing = parseInt(c.curing);
return x;
});
});

Here's a version using the newer spread syntax:
const concrete_cylinders = [
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
}
]
const result = concrete_cylinders.map(o => ({
...o,
...{
curing: parseInt(o.curing),
age: parseInt(o.age)
}
}));
console.log(result);

You could always try using forEach on the array before posting. So for example...
pojo = {
air_content: '',
compaction_method: 1,
concrete_cylinders: [
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
},
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
},
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
}
]
}
pojo.concrete_cylinders.forEach(e => {
e.id = parseFloat(e.id)
e.curing = parseInt(e.curing)
//...anything else you want to change before posting
})
Then pass the object to your axios.post
axios.post('http://localhost:8123/samples/concrete', pojo);
I'm sure there's a way to do this in less lines, but this should solve your problem.

Related

Combine 2 arrays based on their common id [duplicate]

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 4 months ago.
I have 2 different arrays, that i want to combine.
The first one looks like following:
const Cats[] = [
{ id: '1', name: 'Smiley' },
{ id: '2', name: 'Purple' },
]
the second one:
const catAges[] = [
{ id: '4', age: '13', catId: '1' },
{ id: '5', age: '4', catId: '2' },
];
and i want to combine them where id from Cats[] and catId from catAges[] are the same and have a result like following:
{ id: '4', age: '13', cat: { id: '1', name: 'Smiley' } },
{ id: '5', age: '4', cat: { id: '2', name: 'Purple' } },
i get the arrays from 2 different async functions looking like this:
const cats = [await getByCatId("1"), await getByCatId("2")];
const catsAge = await getCatsAges();
But i need help in how i combine these 2 and map them. I've tried something like this but without any success:
const all = (cats, catsAge) =>
cats.map(cats=> ({
...catsAge.find((cats) => (catsAge.catId === cats.id) && catsAge),
...cats
}));
console.log(all(cats, catsAge));
Thankful for any help in how to move forward.
const Cats = [
{ id: '1', name: 'Smiley' },
{ id: '2', name: 'Purple' },
]
const catAges = [
{ id: '4', age: '13', catId: '1' },
{ id: '5', age: '4', catId: '2' },
];
const transformed = catAges.map(item => {
const cat = Cats.find(cat => cat.id === item.catId);
if (cat) {
item.cat = cat;
delete item.catId;
}
return item;
});
console.log(transformed);
The problem with your function is just that you're re-using the cats variable too much, so in your .find comparision you're comparing an element from catsAge (as cats.id) and the catsAge array (as catsAge.catId) which is undefined.
Try this:
const all = (cats, catsAge) =>
cats.map((cat) => ({
...catsAge.find((catsAge) => catsAge.catId === cat.id),
...cat,
}));
Pro tip: Learn+Use Typescript and the compiler would catch these errors for you :)
const Cats = [
{ id: '1', name: 'Smiley' },
{ id: '2', name: 'Purple' },
]
const catAges = [
{ id: '4', age: '13', catId: '1' },
{ id: '5', age: '4', catId: '2' },
];
catAges.map(catage => {
const cat = Cats.find(c => c.id == catage.catId);
if(cat) {
delete catage.catId;
catage.cat = cat;
return catage;
}
});

Create an array of object from given array key

I have array like this .
const test = [
{ student: { id : '1', Name: 'A' }, marks: {
 id: '2', Name: 'B'
} },
{ student: {
 id : '3', Name: 'C' }, marks: { id: '4', Name: 'D' } }
]
Now, from this array of object , I am trying to create two diff arrays which will be having seperate student and marks keys .
const student = [{"student":{"Id": {value: "A"}}}, {"student":{"Id": {value: "B"}}}]
and for marks
const marks = [{"marks":{"Id": {value: "C"}}}, {"marks":{"Id": {value: "D"}}}]
SO, Here what I tried is
test.map((index,item) => {
return [item.student]
})
can any one help me with this ?
Thanks.
You want a new object returned, not a sub array.
Following uses destructuring to simplify the returned object
const test = [
{ student: { id : '1', Name: 'A' }, marks: {
id: '2', Name: 'B'
} },
{ student: {
id : '3', Name: 'C' }, marks: { id: '4', Name: 'D' } }
]
const students = test.map(({student}) => ({student}))
const marks = test.map(({marks}) => ({marks}))
console.log(students)
console.log(marks)

Compare two object arrays and find the indices

I have two arrays,
this is the first array:
const users= [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '118',
firstName: 'c',
lastName: 'd'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '115',
firstName: 'g',
lastName: 'h'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
{
id: '1151',
firstName: 'o',
lastName: 'p'
},
{
id: '1171',
firstName: 'q',
lastName: 'r'
}
];
And this is the second one:
const user2 = [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
]
What I want,
compare these two arrays based on value id and if id is equal in both arrays. I want to find indices for array users for that id which is equal in both arrays.
I tried to compare by filter method and tried findIndex but it is not working.
EDIT:
const result = this.users.filter((obj1) => {
return user2.some((obj2) => {
return obj1.id=== obj2.id; // unique id
});
});
I am not sure how to find indices.
expected output to return the indices of users array for that id which is equal in user2 array
You could reduce the users array to an object indexed by the user id:
const users=[{id:'112',firstName:'a',lastName:'b'},{id:'118',firstName:'c',lastName:'d'},{id:'113',firstName:'e',lastName:'f'},{id:'115',firstName:'g',lastName:'h'},{id:'114',firstName:'i',lastName:'j'},{id:'1151',firstName:'o',lastName:'p'},{id:'1171',firstName:'q',lastName:'r'}];
const user2=[{id:'112',firstName:'a',lastName:'b'},{id:'113',firstName:'e',lastName:'f'},{id:'114',firstName:'i',lastName:'j'},{id:'500',firstName:'i',lastName:'s'},];
const reducedUsers = users.reduce((carry, item, index) => (carry[item.id] = {...item, index}, carry), {});
for (let user of user2) {
const index = reducedUsers.hasOwnProperty(user.id) ? reducedUsers[user.id].index : -1;
console.log(`${user.firstName} ${user.lastName} has index ${index} in users`);
}
Try this:
const myUsers = users.filter(user => user2.filter(usr => usr.id === user.id).length)
You can use map and filter:
const users= [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '118',
firstName: 'c',
lastName: 'd'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '115',
firstName: 'g',
lastName: 'h'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
{
id: '1151',
firstName: 'o',
lastName: 'p'
},
{
id: '1171',
firstName: 'q',
lastName: 'r'
}
];
const user2 = [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
]
function filterArrays(arr1, arr2){
return arr1.map((el1) => {
return arr2.filter((el2) => {
return el2.id == el1.id;
})
}).filter((el) => el.length > 0);
}
console.log(filterArrays(users, user2))
If I understood you correctly, you are interested to get the indexes from both arrays
const users = [{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '118',
firstName: 'c',
lastName: 'd'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '115',
firstName: 'g',
lastName: 'h'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
{
id: '1151',
firstName: 'o',
lastName: 'p'
},
{
id: '1171',
firstName: 'q',
lastName: 'r'
}
];
const user2 = [{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
];
function filterArrays(arr1, arr2) {
return arr1.reduce((tmp, x, xi) => {
const index = arr2.findIndex(y => x.id === y.id);
if (index === -1) {
return tmp;
}
tmp.push({
userInfos: x,
arrayIndex1: xi,
arrayIndex2: index,
});
return tmp;
}, []);
}
console.log(filterArrays(users, user2));
I'm pretty sure lodash's intersectionBy method should do the trick.
https://lodash.com/docs/4.17.15#intersectionBy
// The _.property iteratee shorthand.
_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }]
"This method is like _.intersection except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which they're compared. The order and references of result values are determined by the first array. The iteratee is invoked with one argument:
(value)."
const user2 = [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
]
const users= [
{
id: '112',
firstName: 'a',
lastName: 'b'
},
{
id: '118',
firstName: 'c',
lastName: 'd'
},
{
id: '113',
firstName: 'e',
lastName: 'f'
},
{
id: '115',
firstName: 'g',
lastName: 'h'
},
{
id: '114',
firstName: 'i',
lastName: 'j'
},
{
id: '1151',
firstName: 'o',
lastName: 'p'
},
{
id: '1171',
firstName: 'q',
lastName: 'r'
}
];
const user2Id = user2.map(user => user.id);
users.forEach((user,i) => {
if (user2Id.indexOf(user.id) > 0) {
console.log(user.id + " is present in user2 array at position " + user2Id.indexOf(user.id));
}
});
You can use a Set and do something like this:
function findCommonIndices(array1, array2) {
const tempSet = new Set();
array1.forEach(arr => {
tempSet.add(arr.id);
});
const foundIndices = [];
array2.forEach((arr, index) => {
if (tempSet.has(arr.id)) {
foundIndices.push(index);
}
});
return foundIndices;
}

Javascript - Best/fastest way to add element to query result with fixed value

I have a node.js mysql query:
connection.query("SELECT id AS id, name AS label, status AS status from table;", function(err, rows) {
...
});
The result I'm getting back locks like this:
console.log(getBody)
[ { id: '1',
label: 'Name 01',
status: 'ACTIVE' },
{ id: '2',
label: 'Name 02',
status: 'INACTIVE' },
{ id: '3',
label: 'Name 03',
status: 'ACTIVE' },
{ id: '4',
label: 'Name 04',
status: 'ACTIVE' }];
To further cosume the result ... I need an additional paremeter 'type' with with a fixed value in the array. So result should look like this:
[ { id: '1',
label: 'Name 01',
status: 'ACTIVE',
type: 'ABC' },
{ id: '2',
label: 'Name 02',
status: 'INACTIVE',
type: 'ABC' },
{ id: '3',
label: 'Name 03',
status: 'ACTIVE',
type: 'ABC' },
{ id: '4',
label: 'Name 04',
status: 'ACTIVE',
type: 'ABC' }];
What's the fastest/best way to do this? Looping over the array? How should it look like?
Use the map method:
const newArray = array1.map(element => element = {...element, ...{type: 'ABC'}});
console.log(array1); // array1 won't be changed
console.log(newArray);
Or forEach, this will modify your array:
array1.forEach(element => element.type = 'ABC');
console.log(array1);
var arr = [
{id: '1',label: 'Name 01',status: 'ACTIVE'},
{id: '2',label: 'Name 02',status: 'INACTIVE'},
{id: '3',label: 'Name 03',status: 'ACTIVE'},
{id: '4',label: 'Name 04',status: 'ACTIVE'}];
var new_arr = arr.map(function(el) {
var o = Object.assign({}, el);
o. type = 'ABC';
return o;
})
console.log(arr);
console.log(new_arr);

How to use array.filter + map on an array

I'm trying to filter this array to get the id and convert from a string to a number. I want to use filter and map? Wanting to know how to make it as clear as possible.
var pets = [
{ id: '1', name: 'rupert', readyForHome: 'No', age: 12, personality: ['friendly', 'lazy', 'loving']},
{ id: '2', name: 'mrs fluffy', readyForHome: 'Yes', age: 2, personality: ['affectionate', 'playful', 'shy']},
{ id: '3', name: 'tabitha', readyForHome: 'Yes', age: 4, personality: ['aggressive', 'independent']},
{ id: '4', name: 'lily', readyForHome: 'No', age: 8, personality: ['friendly', 'playful', 'mischievous']},
];
All you need is map to get down to an array of ids as numbers:
pets = pets.map(function(pet) {
return Number(pet.id);
});
var pets=[{id:"1",name:"rupert",readyForHome:"No",age:12,personality:["friendly","lazy","loving"]},{id:"2",name:"mrs fluffy",readyForHome:"Yes",age:2,personality:["affectionate","playful","shy"]},{id:"3",name:"tabitha",readyForHome:"Yes",age:4,personality:["aggressive","independent"]},{id:"4",name:"lily",readyForHome:"No",age:8,personality:["friendly","playful","mischievous"]}];
pets = pets.map(function(pet) {
return Number(pet.id);
});
console.log(pets);
var petIds = pets.map(function (pet) {
petId = parseInt(pet.id);
return petId;
});

Categories