I have an object which is like:
Object {w74: Object, w100: Object,w12: Object,w3: Object}
I need to eleminate one of them to have
Object {w74: Object, w100: Object,w3: Object}
How can remove this in javascript
Use the delete operator:
var ob = {w74: {number: 1}, w100: {number: 2},w12: {number: 3},w3: {number: 4}};
console.log(ob);
delete ob.w74;
console.log(ob);
You can directly delete your value from object by key value
eg.
var arrChildOptions2 = {
w74: Object, w100: Object,w12: Object,w3: Object
};
delete arrChildOptions2.w12;
Use underscore library function called _.pick() http://underscorejs.org/#pick
_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
=> {age: 50}
Related
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed last month.
How can I sort an object, which has an array inside. I need to sort by name in javascript.
My object is:
(4) [{...},{...},{...},{...}]
0: {Age: 10, Name: 'John'}
1: {Age: 25, Name: 'Maria'}
2: {Age: 23, Name: 'Ana'}
3: {Age: 27, Name: 'Pedro'}
The output should be an object like this:
(4) [{...},{...},{...},{...}]
0: {Age: 23, Name: 'Ana'}
1: {Age: 10, Name: 'John'}
2: {Age: 25, Name: 'Maria'}
3: {Age: 27, Name: 'Pedro'}
Sort based on the result of String.prototype.localeCompare (note that Array.prototype.sort also mutates the original array)
const data = [{Age: 10, Name: 'John'},
{Age: 25, Name: 'Maria'},
{Age: 23, Name: 'Ana'},
{Age: 27, Name: 'Pedro'},]
const newData = data.sort((a, b) => a.Name.localeCompare(b.Name));
console.log(newData);
I want to remove every attribute from objects in array except for some of them:
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport: 'n'}]
I am trying with this, but this is only trying to remove one:
arrayOfObjects .forEach(function(v){ delete v.id});
the expected result will be:
var arrayOfObjects = [{name:'oh', school: 'a'},
{name:'em', school: 'b'},
{name:'ge', school: 'c'}]
i don't want to use for loop.
You can map each item in your array to new one, created by reducing list of keys to keep:
const newArray = arrayOfObjects.map(obj => listToKeep.reduce((newObj, key) => {
newObj[key] = obj[key]
return newObj
}, {}))
If you want to mutate original objects and delete properties, you can use two forEach loops and delete operator:
arrayOfObjects.forEach(obj => listToKeep.forEach((key) => {
delete obj[key]
}, {}))
If you can use lodash or similar library, you can pick properties of object, e.g.:
const newArray = arrayOfObjects.map(obj => _.pick(obj, listToKeep))
You can loop over the keys of each JSON object in the arrayOfObjects array and then if the key is not found in the array listToKeep then remove that key:value from the object. And since you want to change the existing arrayOfObjects so you can follow this approach to use delete on the object property.
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport:'n'}];
arrayOfObjects.forEach((obj)=>{
Object.keys(obj).forEach((key)=>{
if(listToKeep.indexOf(key) === -1){
delete obj[key];
}
});
});
console.log(arrayOfObjects);
I want to remove every attribute from objects in array except for some of them:
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport: 'n'}]
I am trying with this, but this is only trying to remove one:
arrayOfObjects .forEach(function(v){ delete v.id});
the expected result will be:
var arrayOfObjects = [{name:'oh', school: 'a'},
{name:'em', school: 'b'},
{name:'ge', school: 'c'}]
i don't want to use for loop.
You can map each item in your array to new one, created by reducing list of keys to keep:
const newArray = arrayOfObjects.map(obj => listToKeep.reduce((newObj, key) => {
newObj[key] = obj[key]
return newObj
}, {}))
If you want to mutate original objects and delete properties, you can use two forEach loops and delete operator:
arrayOfObjects.forEach(obj => listToKeep.forEach((key) => {
delete obj[key]
}, {}))
If you can use lodash or similar library, you can pick properties of object, e.g.:
const newArray = arrayOfObjects.map(obj => _.pick(obj, listToKeep))
You can loop over the keys of each JSON object in the arrayOfObjects array and then if the key is not found in the array listToKeep then remove that key:value from the object. And since you want to change the existing arrayOfObjects so you can follow this approach to use delete on the object property.
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport:'n'}];
arrayOfObjects.forEach((obj)=>{
Object.keys(obj).forEach((key)=>{
if(listToKeep.indexOf(key) === -1){
delete obj[key];
}
});
});
console.log(arrayOfObjects);
I'm getting info from an api, and what I want to do is sum the values inside of it. Let's say that the next code:
function totalPesos(){
$http.get('/api/valueForTest')
.then(function(data){
$scope.resumePesos = data.data.Response;
//console.log($scope.resumePesos);
}
Get the next answer:
[{Id: 60, Name: Chuck, Quantity: 300},
{Id: 61, Name: Arthur, Quantity: 199},
{Id: 62, Name: John, Quantity: 450}]
What I want to do is sum the Quantity. How can I do that? I've tried with:
$scope.resumePesos.reduce(function(a,b){return a + b; });
But the answer was [object Object]
Try the following with pure JS:
var data = [{Id: 60, Name: 'Chuck', Quantity: 300},
{Id: 61, Name: 'Arthur', Quantity: 199},
{Id: 62, Name: 'John', Quantity: 450}]
var sum = data.reduce(function(a, b){
a += b['Quantity'];
return a;
},0)
console.log(sum);
I would write it like this:
$scope.resumePesos.reduce((acc, x) => acc + x.Quantity, 0);
Remember that the 1st argument to the function passed to reduce is the accumulator, and the 2nd is each value you are iterating over, which in this case will be each object. Therefore you need to access the Quantity property of each object. Then you need to pass the initial value of the accumulator as the 2nd argument to reduce itself. Which in this case will be 0, since we want just a number as the result
You should try this instead:
$scope.resumePesos.reduce((a,b) => {return a + b.Quantity}, 0); // Note: 0 at the end
You are doing two things wrong - you haven't set an initial value to the reduce function and you are summing object instead of its numerical property (.Quantity).
var sum = $scope.resumePesos.reduce(function(acummulated, rp) {
return accumulated + rp.Quantity;
}, 0);
Just Use
$scope.sum = $scope.resumePesos.reduce(function(a,b){return a + b.Quantity; }, 0);
You can use lodash and it will be useful if you want some other functions on lodash.
You can do
_.sumBy($scope.resumePesos, 'Quantity');
var data = [
{Id: 60, Name: 'Chuck', Quantity: 300},
{Id: 61, Name: 'Arthur', Quantity: 199},
{Id: 62, Name: 'John', Quantity: 450}
]
console.log(_.sumBy(data, 'Quantity'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Thanx to all, i've tried with all your comments, and worked fine!
Example:
var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}]
var newArr = _.enhance(arr, { married : false });
console.log(newArr); // [{name: 'a', age: 23, married : false}, {name: 'b', age: 24, married : false}]
I'm looking for something to do this. Note, enhance is not present in lodash.
Is it possible to do this with lodash?
If not -- possible addition?
Thanks,
You probably want to extend each of your objects.
mu is too short sort of killed my wordplay while making an excellent point. Updated to create an entirely new array.
var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}];
var newArr = _.map(arr, function(element) {
return _.extend({}, element, {married: false});
});
If you want to add it to the library,
_.enhance = function(list, source) {
return _.map(list, function(element) { return _.extend({}, element, source); });
}
I use ES6 syntax. I think this will help to u.
var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}];
arr.map((element) => {
return element.married = false;
});
console.log(arr); // [{name: 'a', age: 23, married : false}, {name: 'b', age: 24, married : false}]
Using lodash and ES6 arrow notation the solution can become quite short:
const newArr = _.map(arr, o => _.extend({married: false}, o));
Note: I use the object {married: false} as the first argument since mutating this object leaves the original array intact. This means however that married becomes the first field in the resulting object, but this is probably not relevant.
ES6 with Map and Spread
const arr = [{name: 'a', age: 23}, {name: 'b', age: 24}, {name: 'c', age: 25}];
const newArr = arr.map(el => ({ ...el, married: false }));
console.log(newArr);
// [{age: 23, married: false, name: 'a'}, {age: 24, married: false, name: 'b'}, {name: 'c', age: 25, married: false}]
Note: Arrow functions returing an object literal need to wrap the object with parenthesis, e.g., () => ({})
The function lodash has that is closest to what you want is merge: http://lodash.com/docs#merge
The only slight difference between how merge works and what you want to do is you would need to have an array of equal length to arr all that looks like:
var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}];
var marriedArr = [{married : false}, {married : false}];
var newArr = _.merge(arr, marriedArr);
console.log(newArr);
If you attempt to do:
var newArr = _.merge(arr, {married : false});
Then merge will work just like concat.
This comes late and it doesn't involve lodash, but I think the cleanest solution if you want the old data mutable is to use a classic for loop iteration. This way you won't load up the memory with a new array.