How to Do full copy from Slice? [duplicate] - javascript

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 4 years ago.
I an array like this
#observable data = [{a: 1}, {b: 1}, {c:1}];
#observable sampleData = [];
I want to do a slice
this.sampleData = this.data .slice(0, 1);
this.sampleData[0].a = 2;
I want "2" to effect the the record in "sampleData" not in the "data" array what is happening now.

So you basically want to create a copy of every sliced element. You can do it like this:
this.sampleData = this.data.slice(0, 1).map(obj => ({ ...obj }))
Or using Object.assign:
this.sampleData = this.data.slice(0, 1).map(obj => Object.assign({}, obj))
Be advised that this is only a shallow copy, so if your object has nested structure, you would have to perform a deep copy instead.

Related

how to convert this answer to an Object? [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 28 days ago.
This post was edited and submitted for review 28 days ago.
I am trying to convert my answer in an object because it is showing an array in the console?
This is my object
const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};
Here I sort the object according to values:
const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};
const finalAns = Object.entries(myObject).sort(function (a, b) {
return b[1] - a[1];
});
console.log(finalAns);
This is my output of consol.log.
I am getting finalAns as an Array, but I want to print answer as an object and the object should be sorted according to its values?
My understanding is that you are getting the correct answer, but you want to convert it to an object? If so, you could:
var finalAnsObject = JSON.stringify(finalAns)
Updated way (getting a javascript object, not a JSON string):
const newObject = Object.assign({}, ...finalAns.map(element => ({ [element[0]]: element[1] })));

Convert array of data into an object with properties [duplicate]

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 1 year ago.
How do I convert an array into an object with properties:
With the following data:
["Test Scenario ID", "Login-1"]
I would like to return an object with properties:
{1: "Test Scenario ID", 2: "Login-1"} // desired result
With the following, It maps the data into separate objects, but I would like it to be properties of a single object instead of an array of objects:
row.values.map( (e,i) => { return {i: e} })
[{1: "Test Scenario ID"}, {2: "Login-1"}] // the current result
One option is to use Object.fromEntries to turn an array of entries into the object.
const result = Object.fromEntries(
row.values.map((e, i) => [i, e])
);
Another option is to take your array of multiple objects and put it through Object.assign to combine them.
const result = Object.assign(
...row.values.map( (e,i) => ({i: e}))
);
you can use this:
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The Object.assign() method copies all enumerable own properties from
one or more source objects to a target object. It returns the modified
target object.
you can read more about it here on MDN

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

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));.

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));

filter an array of objects based on matching key/value property? [duplicate]

This question already has answers here:
javascript filter array of objects
(8 answers)
Closed 4 years ago.
This is the issue Im trying to solve. I know how to do direct comparison with objects, but Im caught how to make an either or property comparison inside a filter fx.
// tasks are objs with {name: string,id: int}
const taskArray = [task1, task2, task3, task3];
// f(x) needs to take obj param and see if it matches either/or with
// any task obj k/v pair
// my implementation so far, missing something important, help here
const filterTasks = (taskArray, obj) => {
taskArray.filter( task => Object.keys(task) // i know I have to do some equality opperator here but stuck
return taskArray;
}
There it is.
filterTasks will return an array that contains only tasks in the passed array that match at least 1 key/val pair in the passed object.
tArr = [{name: "hi",id: 1},{name: "hola",id: 2},{name: "hello",id: 3},{name: "bye",id: 4}];
const filterTasks = (taskArray, obj) => taskArray.filter( task => Object.keys(task).some( key => obj[key] && obj[key]==task[key]));
console.log(filterTasks(tArr,{name:"hi",id:2}));

Categories