Clone an array and make it unique - Javascript [duplicate] - javascript

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
I have a problem. I have an array of objects. I need to make a copy out of it and make it unique, so when I modify my new array, it doesn't change anything in the original one.
I have tried the following:
let excelData = [...this.state.tableData];
let excelData = this.state.tableData.slice();
let excelData = this.state.tableData.concat();
let excelData = Array.from(this.state.tableData);
But all of the previously listed methods also modify the original array.
Here is my function:
addDynamicExcelColumns() {
let excelData = [...this.state.tableData];
if (this.state.compRentAttr.length > 0) {
excelData.map((d, idx) => {
this.state.compRentAttr.map((i, idx1) => {
excelData[idx][i.AttrName] = d.optionalAttributes[idx1];
});
});
}
return excelData;
}

It is because you are just making a new array with same elements.
when you do let excelData = [...this.state.tableData];, excelData[index] is equal to this.state.tableData[index]
So, what you need to do is a deep clone.
And it's not a perfect way to deep clone, but it looks like you can just use let excelData = JSON.parse(JSON.stringify(this.state.tableData));.

Related

How to compare two different Object keys and update it's value if keys are same in Javascript? [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 2 years ago.
Here i am having two different objects :
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
result should be comparing this above two objects and check if the key are same , then update the oldObject value with newObject . The result has to be like this
let updatedObject = {name:"Dhanush kumar S",age:23,sex:"Male",education:"Btech"}
I tried by doing something like this, but this doesnt help. Your help is much appreciated.
const compareObjects = () => {
for (let [key,value] in oldObject) {
if (newObject.hasOwnProperty(key)) {
oldObject[newObject[key]] = newObject[value]
delete oldObject[key]; //remove old entry
}
}
console.log(oldObject)
}
compareObjects()
You can do this by using the spread syntax.
Just spread the old object first followed by the new object.
Matching keys if any would be updated by the values from the new object and new keys in the new object would be added:
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
const merge = (oldObj, newObj) => {
return {...oldObj, ...newObj};
}
console.log(merge(oldObject, newObject));

Using an object clone method and a for loop to push objects into array, the objects are all still the same reference and are the same in the array [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 2 years ago.
let promiseArr = [];
for (let i = 0; i < ISOarr.length; i++) {
options.body.start_time = ISOarr[i];
let newOptions = cloneOptions(options);
promiseArr.push(newOptions);
}
console.log(promiseArr);
Returns an array of the same object.
Clone method:
cloneOptions = options => {
let clone = {};
for( let key in options ) {
clone[key] = options[key]
}
return clone;
}
So my question is how do I push an object that is not the same reference as the previous objects pushed, because even with it supposedly creating a new clone each loop it still somehow creates the same referenced object.
In the loop if I console.log I get the proper output with the value of the key changed, but once it's pushed into the array and we console.log the array, all objects are the same. Any suggestions would be super helpful. Thank you in advance!
Can you try this
cloneOptions = options => {
return JSON.parse(JSON.stringify(options))
}

How to select a field inside an array inside an object in Javascript [duplicate]

This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 3 years ago.
I have array of object like this :
I need to select only the array which has coreSystemID = 'T24' so I tried credsArr.find() it shows my .find is not a function.
below is my code:
var creds = credsArr.find(x => x.coreSystemID === 'T24')
And I should use the index value like this - credsArr[3053], because the index may vary so I need to select the array which has coreSystemID = 'T24'
let keys = Oject.keys(credsArr).filter(key => credsArr[key].coreSystemID==='T24')
keys will have all the keys of credsArr having credsArr[key].coreSystemID as 'T24'
let systemT24 = credsArr[keys[0]] will give you the object you are looking for given that there is only one object with coreSystemID as 'T24'.
If you have multiple objects that might have coreSystemID as 'T24' you can map it to a new array like this:
let systemT24 = keys.map(key => credsArr[key])
You can use Object.values(credsArr):
var creds = Object.values(credsArr).find(x => x.coreSystemID === 'T24');
or if you need key of the object:
var creds = Object.entries(credsArr).find(x => x[1].coreSystemID === 'T24');
let key = creds[0];
let value = creds[1];

When uniquely updating an object in an array in Javascript, the objects values are all changing [duplicate]

This question already has answers here:
How to update one Javascript object array without updating the other [duplicate]
(3 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I currently have an array of objects called posts.
for(var i = 0; i < posts.length; i++){
let post = posts[i]
let { item, category } = post
let postCollections = categories[category]
for(var col in userCollections[category]){
let items = userCollections[category][col].items
if(items && col){
postCollections[col]['item'] = item
console.log("HERE!, item)
if(item in items){
postCollections[col]['joined'] = true
}else{
postCollections[col]['joined'] = false
}
}
}
posts[i]['collections'] = postCollections
}
When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.
This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:
let postCollections = JSON.parse(JSON.stringify(categories[category]));

Using reduce() changes order of array [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 4 years ago.
Within the example script I have generated two arrays I would like to combine to a single row:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
and
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
What I am trying to achieve is a string like { aLabel = aValue, bLabel = bValue, ... } that can be used to upload into BigQuery (the data upload job works).
I found a piece of code that almost does this, but somehow it changes the order of the elements within the two arrays.
var code = testValue.reduce(function(obj, value, index) {
obj[testHeaders[index]] = value;
return obj
}, {})
However, the result does mix up the order of the arrays as seen below. I am not capable of figuring out why the order changes. As far as I know, reduce() should work its way from left to right in an array.
The returned object is:
{
aLabel = aValue,
dLabel = dValue,
bLabel = bValue,
eLabel = eValue,
cLabel = cValue
}
You can use map and join:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
var res = '{' + testHeaders.map((label, i) => `${label}=${testValue[i]}`).join(',') + '}';
console.log(res);
As vlaz pointed out, you are creating neither a string or a new array, but an object. And just like maps, objects do not have a set order of keys in JavaScript. hence, there is quite a chance of getting another order in the object than in both arrays.

Categories