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;
}
Related
I want to add a key and value(i.e. age:15) to an object which has name as email and remove it(age) from other objects for the below array of object.
[
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
]
i.e. I want the below output.
[
{
name: 'test',
lname: 'last'
},
{
name: 'test1',
lname: 'last1'
},
{
name: 'email',
lname: 'last',
age: 15
},
]
Thanks
What you can do here is find the index of the object that has name as "email". Once you find the object, add the desired age value as a new property called age. Finally, you can use filter to filter the items that doesn't have name as "email" and delete the age property.
var data = [ { name: 'test', lname: 'last', age: 5 }, { name: 'test1', lname: 'last1', age: 15 }, { name: 'email', lname: 'last', }, ]
function myFunction(age) {
let indexOfEmail = data.findIndex(element => element.name == "email")
if (indexOfEmail > -1) {
data[indexOfEmail].age = age
data.filter(element => element.name !== "email").map(sub => delete sub['age'])
}
}
myFunction(15)
console.log(data)
You can do it by using map method, like this:
const data = [
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
];
const newData = data.map(({age, ...rest})=> rest.name == 'email' ? {...rest, age: 15} : rest)
console.log(newData);
You can do like this:
const items = [
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
];
const newItems = items.filter((item) => {
if (item.name.includes("email")) {
return (item.age = 15);
}
if (JSON.stringify(items).includes("email")) {
delete item.age;
}
return item;
});
console.log(newItems);
I have an array of object which must be filtered based on another array, the keys are listed in the allowed array, pls help tired using object.entries and reduce but didn't work
const filter = _.filter;
const data = [{
id: 1,
row: [{
id: 'a',
name: 'ab',
code: 'sdf',
version: 1
},
{
id: 'b',
name: 'bc',
code: 'def',
version: 3
},
{
id: 'c',
name: 'cd',
code: 'afd',
version: 2
},
]
},
{
id: 2,
row: [{
id: 'd',
name: 'ef',
code: 'sdf',
version: 1
},
{
id: 'e',
name: 'gh',
code: 'def',
version: 3
},
{
id: 'f',
name: 'ij',
code: 'afd',
version: 2
},
]
},
{
id: 3,
row: [{
id: 'g',
name: 'kl',
code: 'asd',
version: 2
},
{
id: 'h',
name: 'mn',
code: 'faf',
version: 3
},
{
id: 'i',
name: 'op',
code: 'dfs',
version: 1
},
]
}
]
const allowed = ['id', 'name']
let result = [{
id: 1,
row: [{
id: 'a',
name: 'ab'
},
{
id: 'b',
name: 'bc'
},
{
id: 'c',
name: 'cd'
},
]
},
{
id: 2,
row: [{
id: 'd',
name: 'ef'
},
{
id: 'e',
name: 'gh'
},
{
id: 'f',
name: 'ij'
},
]
},
{
id: 3,
row: [{
id: 'g',
name: 'kl'
},
{
id: 'h',
name: 'mn'
},
{
id: 'i',
name: 'op'
},
]
}
]
result = data.filter(el => el.row.filter(elm => Object.fromEntries(allowed.map(k => [k, elm[k]]))));
console.log(result);
You can create a new array with Array.map.
Logic
Map through the array.
Just spread operator to seperate out row key and rest of keys.
return an object with rest of keys and row key as with the Object.fromEntries
const data = [{
id: 1,
row: [
{ id: 'a', name: 'ab', code: 'sdf', version: 1 },
{ id: 'b', name: 'bc', code: 'def', version: 3 },
{ id: 'c', name: 'cd', code: 'afd', version: 2 },
]
},
{
id: 2,
row: [
{ id: 'd', name: 'ef', code: 'sdf', version: 1 },
{ id: 'e', name: 'gh', code: 'def', version: 3 },
{ id: 'f', name: 'ij', code: 'afd', version: 2 },
]
},
{
id: 3,
row: [
{ id: 'g', name: 'kl', code: 'asd', version: 2 },
{ name: 'mn', code: 'faf', version: 3 },
{ id: 'i', name: 'op', code: 'dfs', version: 1 },
]
}
]
const allowed = ['id', 'name'];
const result = data.map(({ row, ...rest }) => {
return {
...rest,
row: row.map(elm => Object.fromEntries(allowed.map(k => [k, elm[k]])))
}
});
console.log(result);
Long way but it works:
const data = [
{id: 1, row: [
{id: 'a', name: 'ab', code: 'sdf', version: 1},
{id: 'b', name: 'bc', code: 'def', version: 3},
{id: 'c', name: 'cd', code: 'afd', version: 2},
]
},
{id: 2, row: [
{id: 'd', name: 'ef', code: 'sdf', version: 1},
{id: 'e', name: 'gh', code: 'def', version: 3},
{id: 'f', name: 'ij', code: 'afd', version: 2},
]
},
{id: 3, row: [
{id: 'g', name: 'kl', code: 'asd', version: 2},
{id: 'h', name: 'mn', code: 'faf', version: 3},
{id: 'i', name: 'op', code: 'dfs', version: 1},
]
}
];
const allowed = ['id', 'name'];
let res = [];
data.forEach((el) => {
let obj = {};
obj.id = el.id;
obj["row"] = [];
let row = buildArray(el.row);
obj["row"].push(row);
res.push(obj);
})
function buildArray(row) {
r = {};
allowed.forEach((k) => {
r[k] = row[0][k];
})
return r;
}
console.log(res)
I have the below user information.
[ { ID: '21',NAME: 'JACK',MARKS: 75,GRADE: 'A',RESULT: 'PASS ' },
{ ID: '21',NAME: 'JACK',MARKS: 32,GRADE: 'F',RESULT: 'FAIL' },
{ ID: '87',NAME: 'SAM',MARKS: 91,GRADE: 'A+',RESULT: 'PASS' },
{ID: '7',NAME: 'TOM',MARKS: 100,GRADE: 'A+',RESULT: 'PASS' },
{ ID: '21',NAME: 'JACK',MARKS: 61,GRADE: 'B',RESULT: 'PASS' },
{ ID: '87',NAME: 'SAM',MARKS: 72,GRADE: 'B',RESULT: 'PASS ' }
]
Goal is to generate a new object called INFO with fields MARKS,GRADE,RESULT. Also since there are repetitive id's this INFO propery needs to be grouped with its respective id and generate the below result
[{ID:'21',INFO:[{MARKS: 75,GRADE: 'A',RESULT: 'PASS ' },{MARKS: 32,GRADE: 'F',RESULT: 'FAIL'},{MARKS: 61,GRADE: 'B',RESULT: 'PASS']},
{ID:'87',INFO:[MARKS: 91,GRADE: 'A+',RESULT: 'PASS'],[MARKS: 72,GRADE: 'B',RESULT: 'PASS ']},
{ID:'7',INFO:{ MARKS: 100,GRADE: 'A+,RESULT: 'PASS'}
]
I am trying to use the below code but it doesn't generate the expected results
console.log(groupByField(data,'id'))
function groupByField(data, field) {
var outObject = data.reduce(function (a, e) {
let estKey = (e[field]);
(a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e);
return a;
}, {});
return outObject
}
can someone help me?
function transform(info) {
return info.reduce((pre, cur) => {
let ext = pre.find(d => d.ID === cur.ID);
let {ID, MARKS, GRADE, RESULT} = cur;
if (ext) {
ext.INFO = ext.INFO instanceof Array
? [...ext.INFO, {MARKS, GRADE, RESULT}]
: [ext.INFO, {MARKS, GRADE, RESULT}];
} else {
pre.push({ID, INFO:{MARKS, GRADE, RESULT}});
}
return pre;
}, []);
}
Happy coding!
You can achieve the desired result using Map and forEach
const arr = [
{ ID: "21", NAME: "JACK", MARKS: 75, GRADE: "A", RESULT: "PASS " },
{ ID: "21", NAME: "JACK", MARKS: 32, GRADE: "F", RESULT: "FAIL" },
{ ID: "87", NAME: "SAM", MARKS: 91, GRADE: "A+", RESULT: "PASS" },
{ ID: "7", NAME: "TOM", MARKS: 100, GRADE: "A+", RESULT: "PASS" },
{ ID: "21", NAME: "JACK", MARKS: 61, GRADE: "B", RESULT: "PASS" },
{ ID: "87", NAME: "SAM", MARKS: 72, GRADE: "B", RESULT: "PASS " },
];
const map = new Map();
arr.forEach((o) => {
const { ID, NAME, ...rest } = o;
if (map.has(o.ID)) map.get(o.ID).push(rest);
else map.set(o.ID, [rest]);
});
const result = [];
for (let [ID, INFO] of map) {
if (INFO.length === 1) result.push({ ID, INFO: INFO[0] });
else result.push({ ID, INFO });
}
console.log(result);
Here is refactoring of the flagged duplicate to fit your specific needs, specifically grouping inside a nested array for each object.
It is a fairly standard 'group-by' using Array.prototype.reduce() in combination with destructuring assignment to isolate only the properties we need.
const input = [ { ID: '21', NAME: 'JACK', MARKS: 75, GRADE: 'A', RESULT: 'PASS ' }, { ID: '21', NAME: 'JACK', MARKS: 32, GRADE: 'F', RESULT: 'FAIL' }, { ID: '87', NAME: 'SAM', MARKS: 91, GRADE: 'A+', RESULT: 'PASS' }, { ID: '7', NAME: 'TOM', MARKS: 100, GRADE: 'A+', RESULT: 'PASS' }, { ID: '21', NAME: 'JACK', MARKS: 61, GRADE: 'B', RESULT: 'PASS' }, { ID: '87', NAME: 'SAM', MARKS: 72, GRADE: 'B', RESULT: 'PASS ' }, ];
const result = Object.values(
input.reduce(function (r, { ID, NAME, ...rest }) {
(r[ID] ??= { ID, INFO: [] }).INFO.push(rest);
return r;
}, Object.create(null))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The above snippet makes use of logical nullish assignment (??=). For compatibility you can use an || short-circuit instead if need be.
(r[ID] || (r[ID] = { ID, INFO: [] })).INFO.push(rest);
Using lodash groupBy() : https://lodash.com/docs/4.17.15#groupBy
const data = [
{ ID: '21', NAME: 'JACK', MARKS: 75, GRADE: 'A', RESULT: 'PASS ' },
{ ID: '21', NAME: 'JACK', MARKS: 32, GRADE: 'F', RESULT: 'FAIL' },
{ ID: '87', NAME: 'SAM', MARKS: 91, GRADE: 'A+', RESULT: 'PASS' },
{ ID: '7', NAME: 'TOM', MARKS: 100, GRADE: 'A+', RESULT: 'PASS' },
{ ID: '21', NAME: 'JACK', MARKS: 61, GRADE: 'B', RESULT: 'PASS' },
{ ID: '87', NAME: 'SAM', MARKS: 72, GRADE: 'B', RESULT: 'PASS ' },
];
const grouped = _.groupBy(data, 'NAME');
Results :
grouped:, {
JACK: [
{ ID: '21', NAME: 'JACK', MARKS: 75, GRADE: 'A', RESULT: 'PASS ' },
{ ID: '21', NAME: 'JACK', MARKS: 32, GRADE: 'F', RESULT: 'FAIL' },
{ ID: '21', NAME: 'JACK', MARKS: 61, GRADE: 'B', RESULT: 'PASS' }
],
SAM: [
{ ID: '87', NAME: 'SAM', MARKS: 91, GRADE: 'A+', RESULT: 'PASS' },
{ ID: '87', NAME: 'SAM', MARKS: 72, GRADE: 'B', RESULT: 'PASS ' }
],
TOM: [ { ID: '7', NAME: 'TOM', MARKS: 100, GRADE: 'A+', RESULT: 'PASS' } ]
}
An approach which transforms, groups and collects items within a single reduce task and no additional iterations within each reduce step might look similar to the following one ...
function groupCollectAndTransformItemById(collector, { ID, NAME, ...rest }) {
const { index, list } = collector;
let infoGroup = index[ID]?.INFO
if (Array.isArray(infoGroup)) {
// push into an already existing grouped array.
infoGroup.push(rest);
} else if (infoGroup) {
// create an array for more than just one grouped item.
index[ID].INFO = [infoGroup, rest];
} else {
// create a new group-item with
// its initial ID and first INFO data ...
infoGroup = index[ID] = { ID, INFO: rest };
// ... and push a reference into the collector's/
// accumulator's `list` array which also holds
// the final result of the reduce process.
list.push(infoGroup);
}
return collector;
}
const sampleData = [
{ ID: '21',NAME: 'JACK', MARKS: 75, GRADE: 'A', RESULT: 'PASS' },
{ ID: '21',NAME: 'JACK', MARKS: 32, GRADE: 'F', RESULT: 'FAIL' },
{ ID: '87',NAME: 'SAM', MARKS: 91, GRADE: 'A+', RESULT: 'PASS' },
{ ID: '7', NAME: 'TOM', MARKS: 100, GRADE: 'A+', RESULT: 'PASS' },
{ ID: '21',NAME: 'JACK', MARKS: 61, GRADE: 'B', RESULT: 'PASS' },
{ ID: '87',NAME: 'SAM', MARKS: 72, GRADE: 'B', RESULT: 'PASS' },
];
console.log(
sampleData
.reduce(groupCollectAndTransformItemById, {
index: {},
list: [],
}).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
What is the best way to convert
const mockResults = [
[{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' }],
[{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' }],
[{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }]
];
to
const mockResults = [
{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' },
{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' },
{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }
];
The whole task is to transform mockResults to requiredFormat, that's why I need to remove nested arrays:
const requiredFormat = [
{
status: 'WRONG',
data: [{ user: {firstName: '1', lastName: '1'}}, { user: {firstName: '2', lastName: '2'}}],
},
{
status: 'CORRECT',
data: [{ user: {firstName: '3', lastName: '3'}}],
},
];
Here's what I tried so far:
https://jsfiddle.net/9uLje3sg/
Thanks!
You can use flat method from Array javascript object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
If you want to change the source of data and change the shape of it, using map and reduce methods can help you.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
In your precise example reduce would fit as you are creating a new object grouping per status property.
const mockResults = [
[{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' }],
[{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' }],
[{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }]
];
const flattedAndReduced = mockResults.flat().reduce( (acc, curr)=>{
const statusIndex = { 'WRONG' : 0, 'CORRECT': 1 };
acc[statusIndex[curr.status]].data.push({ user: curr.user} );
return acc;
}, [
{
status: 'WRONG',
data: [],
},
{
status: 'CORRECT',
data: [],
}
]
);
console.log(flattedAndReduced);
Use the function map as follow which returns an array with the desired objects.
let result = mockResults.map(([user]) => user);
That approach is assuming there is only one index per array from the original array.
According to the approach for requiredFormat
You can use the function reduce for grouping and the function Object.values for getting the desired output.
const mockResults = [
[{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' }],
[{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' }],
[{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }]
];
let requiredFormat = Object.values(mockResults.reduce((a, [{user, status}]) => {
(a[status] || (a[status] = {data: [], status})).data.push(user);
return a;
}, Object.create(null)));
console.log(requiredFormat);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Simply use Array.prototype.map() to return the object from first index.
Please Note: variable declared with const can not be modified, use *let instead.
let mockResults = [
[{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' }],
[{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' }],
[{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }]
];
mockResults = mockResults.map(i => i[0]);
console.log(mockResults);
const mockResults = [
[{ user: { firstName: '1', lastName: '1' }, status: 'WRONG' }],
[{ user: { firstName: '2',lastName: '2' }, status: 'WRONG' }],
[{ user: { firstName: '3',lastName: '3' }, status: 'CORRECT' }]
];
const requiredFormat = [
{status: 'WRONG', data: []},
{status: 'CORRECT', data: []},
];
for(let [{user,status}] of mockResults) {
requiredFormat[ status==="WRONG" ? 0 : 1].data.push({user});
}
console.log(requiredFormat);
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.