- In the dataToSend object
- I want to access CreateValues and filter(startsWith('FLD_STR_') && typeof el.value === 'object')
- Once I retrieve the field, I remove the array newly created and I push the data to a new object createFileValues.
- I then want to add createFileValue to the dataToSend Object
- And I delete the element filtered from the initial createValues array
//original object
const dataToSend = {
ID: 748817,
createValues: [{
field: "FLD_STR_101",
value: 'hello',
},
{
field: "FLD_STR_102",
fileName: "doc.pdf",
value: {
field: 'FLD_STR_102',
fileName: 'bulletin_paie_avril.pdf',
value: 'jkhkjhkhkjh'
}
}
]
}
// code in progress
const test = dataToSend.createValues.filter(
(el) => el.field.startsWith('FLD_STR_') && typeof el.value === 'object'
);
dataToSend.createFileValues = test;
//output desired
const dataToSend = {
createValues: [{
field: "FLD_STR_101",
value: 'hello',
}],
createValues: [{
field: "FLD_STR_101",
value: 'hello',
}
],
createFileValues:{
field: 'FLD_STR_102',
fileName: 'bulletin_paie_avril.pdf',
value: 'jkhkjhkhkjh'
}
}
CodePudding user response:
You should use splice using index of the element you want.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
You will need to use a loop;
const test = dataToSend.createValues.filter(
(el) => el.field.startsWith('FLD_STR_') && typeof el.value === 'object'
);
dataToSend.createFileValues = test;
test.foreach( ( obj ) => {
dataToSend.createValues.splice( 0, 1, obj );
}
If you really for some reason don't want to use a loop and you know you will ever only want 1 item then you could do
const test = dataToSend.createValues.filter(
(el) => el.field.startsWith('FLD_STR_') && typeof el.value === 'object'
);
dataToSend.createFileValues = test;
dataToSend.createValues.splice( 0, 1, test[0] );