Remove array element based on object property
One possibility:
myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});
Please note that filter
creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray
with the new reference. Use with caution.
remove objects from array by object property
I assume you used splice
something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i
for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => { let end = 0;
for (let i = 0; i < array.length; i++) { const obj = array[i];
if (predicate(obj)) { array[end++] = obj; } }
array.length = end;};
const toDelete = new Set(['abc', 'efg']);
const arrayOfObjects = [{id: 'abc', name: 'oh'}, {id: 'efg', name: 'em'}, {id: 'hij', name: 'ge'}];
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));console.log(arrayOfObjects);
javascript remove all objects from array based on property value
Why not use filter
MDN ?
const myarr = [
{
name: 'foo',
school: 'hoo'
},{
name: 'foo',
school: 'xooo'
},{
name: 'bar',
school: 'xooo'
}
];
const filteredArray = myarr.filter(obj => obj.name !== 'foo');
Example: https://repl.it/repls/SimultaneousSentimentalForms
Edited to match the comment.
How to remove object property from an array of objects if the value is 0
Array#forEach
doesn't return an array.
To achieve your desired output, in each iteration, use Object#entries
to get the key-value pairs of the current object, and Array#filter
to filter the ones where the value
is zero. To construct the resulting object again, use Object#fromEntries
:
const data = [ { percent: 123, unit: -1 }, { percent: 456, unit: 0 }, { percent: 0, unit: 5}, { percent: 789, unit: -3 } ];
const newData = data.map(e =>
Object.fromEntries(
Object.entries(e).filter(([key, value]) => value !== 0)
)
);
console.log(newData)
Remove Object from Array using JavaScript
You can use several methods to remove item(s) from an Array:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, someArray.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
If you want to remove element at position x
, use:
someArray.splice(x, 1);
Or
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter
, or Array.splice
combined with Array.findIndex
(see MDN).
See this Stackblitz project or the snippet below:
// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" );
log(`let noJohn = someArray.filter( el => el.name !== "John")`,
`non destructive filter [noJohn] =`, format(noJohn));
log(`**someArray.length ${someArray.length}`);
// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("",
`someArray2 = someArray2.filter( el => el.name !== "John" )`,
`destructive filter/reassign John removed [someArray2] =`,
format(someArray2));
log(`**someArray2.length after filter ${someArray2.length}`);
// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("",
`someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1),`,
`destructive splice /w findIndex Brian remains [someArray3] =`,
format(someArray3));
log(`**someArray3.length after splice ${someArray3.length}`);
// if you're not sure about the contents of your array,
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", `someArray4.splice(indx, indx >= 0 ? 1 : 0)`,
`check findIndex result first [someArray4] = (nothing is removed)`,
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);
// -- helpers --
function format(obj) {
return JSON.stringify(obj, null, " ");
}
function log(...txt) {
document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}
function getArray() {
return [ {name: "Kristian", lines: "2,5,10"},
{name: "John", lines: "1,19,26,96"},
{name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**
</pre>
Remove property for all objects in array
The only other ways are cosmetic and are in fact loops.
For example :
array.forEach(function(v){ delete v.bad });
Notes:
- if you want to be compatible with IE8, you'd need a shim for forEach. As you mention prototype, prototype.js also has a shim.
delete
is one of the worst "optimization killers". Using it often breaks the performances of your applications. You can't avoid it if you want to really remove a property but you often can either set the property toundefined
or just build new objects without the property.
How to remove object from array if property in object do not exist
You can use .filter()
, Object.keys()
, and .includes()
let input = [ { id: '1', date: '2017-01-01', value: 2}, { id: '2', date: '2017-01-02', value: 3}, { id: '3', value: 3 }, { id: '4', date: '2017-01-02', value: 3 }] let output = input.filter(obj => Object.keys(obj).includes("date")); console.log(output);
JavaScript - delete object properties in array of objects
I can think of two ways
function stripObjProps(arr) {
let newArr = _.clone(arr);
for (let i = 0; i < newLay.length; i += 1) {
[
"isBounded",
"isDraggable",
"isResizable",
"maxH",
"maxW",
"minH",
"minW",
"resizeHandles",
"moved",
"static"
].forEach(k => delete newArr[i][k]);
}
}
or - assuming newLay
is a typo
function stripObjProps(arr) {
return arr.map(item => {
let {
isBounded,
isDraggable,
isResizable,
maxH,
maxW,
minH,
minW,
resizeHandles,
moved,
static,
...ret
} = item;
return ret;
});
}
NOTE: no need for _.clone
in this second example, since you aren't doing a deep clone, map returns a new array with a new object (...ret
)
However, I don't use lodash, so there may be an even better way with that library
Remove objects from a deeply nested object array by property value
The following recursively returns a new array without mutating the original
const content = [{
prop1: "someValue",
prop2: "someValue",
content: [{
prop2: "someValue",
prop3: "someValue",
myProperty: "myValue"
},
{
prop1: "someValue",
prop3: "someValue",
myProperty: "otherValue"
}
]
},
{
prop5: "someValue",
prop2: "someValue"
}
]
function removeObjects(content) {
return content.reduce((arr, obj) => {
if (obj["myProperty"] && obj["myProperty"] === "myValue") {
return arr
} else if (obj["content"] && obj["content"].length) {
arr.push({ ...obj,
content: removeObjects(obj["content"])
})
return arr
} else {
arr.push(obj);
return arr;
}
}, []);
}
console.log(removeObjects(content))
Related Topics
Binding Arrow Keys in Js/Jquery
Replace Multiple Characters in One Replace Call
How to Run Gulp Tasks Sequentially One After the Other
JavaScript Scroll Event for Iphone/Ipad
Declaring Multiple Variables in JavaScript
Emberjs: How to Load Multiple Models on the Same Route
Display Date/Time in User's Locale Format and Time Offset
How to Replace While Loops with a Functional Programming Alternative Without Tail Call Optimization
How to Write a Named Arrow Function in Es2015
What Does "This" Mean in Jquery
Group Objects by Multiple Properties in Array Then Sum Up Their Values
Sorting a JavaScript Object by Property Name
Why Does a While Loop Block the Event Loop
How to Set Focus on an Input Field After Rendering
How to Draw Smooth Curve Through N Points Using JavaScript HTML5 Canvas
How to Redirect with JavaScript
Difference Between Settimeout with and Without Quotes and Parentheses