I am trying to insert new keys inside my array which i basically extracted from the parent array. I can't find the reason that just by inserting my new keys to the extracted array causing change in the main array which is there inside my store.
Here is the method in which i am trying to add new key value pairs in my custom array
const array = [{"integrationTypeId":1,"type":"aptus","fields":[{"name":"base_url"},{"name":"hash_key"}]}]
function runArray(){
let connectorObject= {}
let newArray
if (array.length > 0) {
connectorObject =
array.find(
(c) => c.integrationTypeId === 1,
);
newArray = connectorObject.fields
newArray !== undefined &&
newArray.map((object) => {
return Object.assign(object, {
inputType: "textField",
value: object.name,
})
})
}
console.log(JSON.stringify(newArray))
console.log(JSON.stringify(array))
}
runArray();
Here are the outputs :
Console 1. : newArray
[{"name":"base_url","inputType":"textField","value":"base_url"},{"name":"hash_key","inputType":"textField","value":"hash_key"}]
Console 2. : Parent Array
[{"integrationTypeId":1,"type":"aptus","fields":[{"name":"base_url","inputType":"textField","value":"base_url"},{"name":"hash_key","inputType":"textField","value":"hash_key"}]}]
what makes it modified with newArray values in it.
even tried with : newArray.map(obj => ({ ...obj, [inputType]: "textField"}));
It is important to know that the Javascript arrays and Objects are passed by reference. which means that if you modify an array or object, it will be reflected in all references to that array or object.
In this case, it is too much-nested array-->object-->array-->object. Thus while extracting make sure you make a new array or object. Here I have used ES6 ...
syntax to create a new array/object. Just using =
copies it's reference and thus changes are reflected.
The code below is not optimized, but I hope you get the point.
const array = [
{
integrationTypeId: 1,
type: "aptus",
fields: [{ name: "base_url" }, { name: "hash_key" }],
},
];
function runArray() {
let connectorObject = {};
let newArray = [];
if (array.length > 0) {
connectorObject = {
...array.find((c) => c.integrationTypeId === 1), //Creating brand new copy of array object
fields: [...array.find((c) => c.integrationTypeId === 1).fields], //Creating brand new copy of fields array
};
newArray = connectorObject.fields.map((field) => { //Creating brand new copy of fields array object
return { ...field };
});
newArray.map((object) => {
Object.assign(object, {
inputType: "textField",
value: object.name,
});
});
}
console.log(JSON.stringify(newArray));
console.log(JSON.stringify(array));
}
runArray();