does anyone know how I can remove a surrounding array from an array of objects? In my case, I only have one object in this array. [{"id":"6","email":"test#test.com"}] Also, would the solution work in the case of multiple objects in the array? Thanks!
You have an array of objects. That's great, because it's the easiest way to store and manipulate lists of records.
You can use array methods like .map that allow you to treat each record separately, telling it what to do individually with each element. That's also great, because it basically "removes the element from the array" while still processing the whole array, which is what I think you're after.
Simple example to create a dropdown:
const data = [{"id":"6","email":"test#test.com"}, {"id":"12","email":"test2#test.com"}];
const drawEmailDropdown = () => {
let options = data.map(d => `<option value='${d.id}'>${d.email}</option>`);
return `<select>` + options.join("") + `</select>`;
};
document.querySelector("#container").innerHTML = drawEmailDropdown();
<div id="container"></div>
Related
I have two associative arrays and want to push one completely to the other.
my current code:
LT_WORK_PACKAGE.data[i].STOCK_DOCCAT = stock_data.STOCK_DOCCAT;
LT_WORK_PACKAGE.data[i].STOCK_DOCNO = stock_data.STOCK_DOCNO;
LT_WORK_PACKAGE.data[i].STOCK_ITMNO = stock_data.STOCK_ITMNO;
im looking for something like this:
LT_WORK_PACKAGE.data[i].push(stock_data);
.push is for adding items to an array. You do have an object , and to copy multiple properties into an object,you can use Object.assign:
Object.assign(
/*to:*/ LT_WORK_PACKAGE.data[i],
/*from:*/ stock_data
);
You can use LT_WORK_PACKAGE.data[i] = stock_data.
Note that the previous content (if it exists) of LT_WORK_PACKAGE.data[i] will be replaced by a reference to stock_data. Any changes made in stock_data will be done in LT_WORK_PACKAGE.data[i] If you want a copy, you can use : LT_WORK_PACKAGE.data[i] = JSON.parse(JSON.serialize(stock_data))
I've a react application, and i've found a bug where i'm filtering an array for searching the current item the user has selected and then i'm going to do stuff with it...but, didn't know that filter function return a reference to the array's item, so, every change i made to the selected item i'm doing the same to the prop array.
const pippo = maledettoArray.filter(item => item.id === idInfame)[0];
How can i filter the prop array to get the specific item without changing it?
You can use find method instead of filter which returns first match and exits the loop.
const pippo = maledettoArray.find(item => item.id === idInfame)
To create shallow copy of the object you can use Object.assign or spread syntax.
const clone = {...pipo}
If you want to create deep copy of the nested object then you could use Lodash _.cloneDeep(value) method.
First of all, I would recommend you use the find function instead of filter to avoid the empty array return and undefined at [0]
Secondly, yes, the object reference would be returned. To avoid this, you can use Object.assign({}, originalObject) or using the spread syntax {...originalObject} . A potential problem would be with nested objects which could still be a problem.
Probably this article can help you in such case https://medium.com/#Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d
I'm trying to replace array elements (generic objects) with their alternatives (specific Objects), but objects within the original array remain unchanged.
class SpecificObject{
}
this.Objects = [{},{}];
this.Objects.map((signer,index) => {
//convert json generics to js objects
this.Objects[index] = new SpecificObject(signer);
});
console.log(this.Objects);
Not sure if the code snippet illustrates the problem correctly, but what i expect to see is:
[
SpecificObject{},
SpecificObject{}
]
I even tried cloning the original object to do the iteration but it didn't help. Must be missing something stupid. Is there a way to achieve what i need with lodash?
Edit(followed the answer advise):
Now i do the following:
console.log('signers-before', this.Signers);
this.Signers.map(signer => new SigningTableSigner(signer));
console.log('signers-after',this.Signers);
And this is what i get in my log(object still remain generic):
Edit2
Oops, i forgot the assignment. this.Signers =
now like this everything works as expected:
console.log('signers-before', this.Signers);
this.Signers = this.Signers.map(signer => new SigningTableSigner(signer));
console.log('signers-after',this.Signers);
There is no need to modify the collection while you are iterating it. Just return the object from the map.
this.Objects = this.Objects.map((signer,index) => new SpecificObject(signer));
Map is used when you wants to return an array. You can just use forEach for what you are trying to do. But I think this will look better
this.Objects = this.Objects.map(signer => new SpecificObject(signer))
You don't use map correctly. You should be just returning objects inside arrow functions. map actually returns new array, which contains elements which were created by applying function you have provided. Because of that you also have to reassign result ot this.Objects.
this.Objects = this.Objects.map(signer => {
//convert json generics to js objects
return new SpecificObject(signer);
})
I've looked through many stack overflow questions, but none seem to quite answer my question. I have an array of objects, which I would like to reduce by deleting all objects where the key and value are the same.
So my array of objects would be:
[{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
The end result should be:
[{a:1},{a:2},{c:3},{b:1},{c:4}]
I've tried using filer and map, but I can only get the first object in the array, rather than all the objects that have different key/value pairs in the array. I've also tried using filter and findIndex, but with the same problem.
I also can't filter the objects before pushing them into the array.
Can someone point me in the right direction?
You can compare the two items using JSON.stringify(). We then add to a new array using reduce, if it is in the array we don't add it otherwise we do add it.
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = array.reduce((res, itm) => {
// Test if the item is already in the new array
let result = res.find(item => JSON.stringify(item) == JSON.stringify(itm))
// If not lets add it
if(!result) return res.concat(itm)
// If it is just return what we already have
return res
}, [])
console.log(unique)
Alternatively you could use a Set (as Fissure King metions) to make a unique list of items like this:
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = [...new Set(array.map(itm => JSON.stringify(itm)))].map(i => JSON.parse(i))
console.log(unique)
Assuming that all your object are of different types(different properites) and are not complex in nature i.e., not nested objects..
Create a array list(which will act as multi dimensional array).
let uniqueArr = [];
Loop through your array which contains duplicates with Arr.forEach();
Get property of the object using
Object.getPropertyNames(item);
Check wether this type of object type already exists in your uniqueArr ,if not add the property type.
uniqueArr.push({property:[]});
If the property already exists in the uniqueArr, check whether the current property value exits in the property array inside uniqueArr.
If the property doesn't not exist add the new property to the respective property array.if the property exits skip and run the loop for next object.
Once loop completed, create resultArr with the help of the
uniqueArr.
Sample : uniqueArr [ {a:[1,2]}, {b:[1]}, {c:[3]} ];
var a = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}];
var newData = [];
a.map(ele=>JSON.stringify(ele)).forEach(ele=>{
if(newData.indexOf(ele) === -1){
newData.push(ele)
}
});
newData.map(ele=>JSON.parse(ele))
console.log(newData);
Working on a React app and have a this.state.filesAccepted which is an array of objects. It looks like this:
I also have an array of strings called filenames that looks like the following:
I'd like to compare the two and if there is a match, the object should be removed from the array in this.state.filesAccepted. For example, if a string in filenames ("eicartest1") matches the key in filesAccepted (key: "eicartest1"), it should remove that object from the array.
There may be a more efficient and cleaner way of doing this, but for the comparison, I think I need to do two loops like the following:
_.map(filenames, f => {
_.map(this.state.filesAccepted, fa => {
if (f === fa.key) {
delete entire object from array;
}
});
});
How should I be handling the delete? Is there a more efficient way to make this comparison besides map twice?
The following should work:
this.state.filesAccepted.filter(
file=>!filenames.includes(file.key)
)
That results in an array that only has items where the src is not in filenames
To create a new state with the new filesAccepted you can do:
this.setState({
...this.state,
filesAccepted:this.state.filesAccepted.filter(
file=>!filenames.includes(file.key)
)
})
You can use Array.prototype.filter() to remove unmatched items
const filesAccepted = this.state.filesAccepted.filter(obj => !_.includes(filenames, obj.key));
this.setState({filesAccepted});