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);
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 have two array like this
const arr1 = [{code: 'a', name: 'x'}];
const arr2 = [{code: 'a', name: 'x'}, {code: 'b', name: 'y'}];
Here I want to check the code vale in first array object is present in the second array's code value.
For this I tried like this but it returned false
arr1.every(item => arr2.includes(item))
How can I check the code value in first array object is present in the second array object
You can do something like this
const arr1 = [{code: 'a', name: 'x'}];
const arr2 = [{code: 'a', name: 'x'}, {code: 'b', name: 'y'}];
const codeValues = new Set(arr2.map(({code}) => code));
const isPresent = arr1.some(item => codeValues.has(item.code));
console.log(isPresent);
Is there a function that can convert an array ['A', 'B', 'C'] to an object array [{name: 'A'}, {name: 'B'}, {name: 'C'}]?
Or do I need to write a util function? It is no big deal to write one but curious if a well known function is already there.
Thanks
You can use Array.prototype.map(). Array.map is a method that will iterate through each element in an Array and return an output based on the callback. You can find more information on Array.map on the MDN: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map
And here is a working example: https://jsbin.com/qawener/edit?js,console
In this example, we take each element of the array and we return an object with {"name": }. This then creates the newArray array that will have [{name: 'A'}, {name: 'B'}, {name: 'C'}].
const originalArray = ["a", "b", "c"];
let newArray = originalArray.map(element => { return {name: element}; });
console.log(newArray);
Map works very well for these types of situations.
const array = ['A', 'B', 'C'];
const myNewArray = array.map(function(map, i) {
const dict = {"name":array[i]}
return dict;
}, {});
console.log(myNewArray)
Beside the given answer, you may use short hand properties for the object.
const
names = ["a", "b", "c"],
result = names.map(name => ({ name }));
console.log(result);
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);
}
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.