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.
Related
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 am working in vanilla JavaScript.
I have two arrays of the same length.
Each of them is containing objects.
I need to create one array with objects combined.
How?
So, in code, my input is:
const arr1 = [{name: "John"}, {name: "Peter"}];
const arr2 = [{age: 56}, {age: 22}]
Desirable output:
const arr3 = [{name: "John", age: 56}, {name: "Peter", age: 22}]
I saw solution that ES6 offers, and it goes like this:
const object1 = {
name: 'John'
}
const object2 = {
age: 56
}
const object3 = {...object1, ...object2 }
That works just great! I would like to implement this same solution in this example whit objects in arrays using this spread operator. How? :)
Thank you.
Using Array.prototype.map() and spread syntax:
const arr1 = [{ name: 'John' }, { name: 'Peter' }];
const arr2 = [{ age: 56 }, { age: 22 }];
const arr3 = arr1.map((v, i) => ({ ...v, ...arr2[i] }));
console.log(arr3);
Another option
const arr1 = [{name: "John"}, {name: "Peter"}];
const arr2 = [{age: 56}, {age: 22}];
const result = [];
for(let i = 0; i < arr1.length; i++) result.push(Object.assign(arr1[i], arr2[i]));
console.log(result)
P.S, also as #charlietfl mentioned: if you don't want to mutate objects in arr1 start with empty object ... Object.assign({},arr1[i], arr2[i])
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 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}
I have two arrays containing the same elements but in different order, like this:
var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}];
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];
In this case of course a simple reverse() would do the trick but it might be an array with 10 objects in a random order.
Since both arrays always contains some common properties (name) I should be able to rearrange one array to match the other based on name.
Any tips on how to go about this?
Maybe something like this then? But this assumes that each object in the array has the name property.
var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}];
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];
function sortArray(arr) {
arr.sort(function(a, b) {
return a.name > b.name;
});
}
sortArray(arr1);
sortArray(arr2);
I think you can scan the arranged array and search elements in the second array and put them in a new array.
new_array;
foreach(element in array_ordered)
{
temp = search(element[name], array_unordered);
if(temp != null)
new_array.add(temp);
}