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);
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);
I would like to get result like
arr=['A','B','C','D']
from the object like below.
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ] }
How to reach out to concatenate to array?
If someone has opinion, please let me know.
Thanks
You can get the values using Object.values() and to get them in one array you can use Array.prototype.flat():
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var arr = Object.values(obj).flat()
console.log(arr)
You can make use of Object.values and spread it into a single array with Array.prototype.concat since Array.prototype.flat is not supported in older browsers
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var vals = [].concat(...Object.values(obj))
console.log(vals)
Quick solution is to create an array of obj1 and concat the obj2.
const arr = [obj.obj1].concat(obj.obj2);
You can use reduce() followed by Object.values()
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ]
};
const res = Object.values(obj).reduce((acc, curr) => [...acc, ...curr], []);
console.log(res);
I am receiving the following array from an API response:
[
{group: '1', , value: 'a'}
{group: '1', , value: 'b'}
{group: '2', , value: 'c'}
{group: '2', , value: 'd'}
]
I want to convert it to the following (want order of groups as received, values can be ordered in any way):
[
{group: '1', values: ['b', 'a'] },
{group: '2', values: ['c', 'd'] },
]
Which Javascript function will be the most efficient to convert it?
I am able to do this by:
let result = [];
data.reduce((groupNumber, input) => {
if (!groupNumber[input.group]) {
groupNumber[input.group] = {group: input.group, values: []};
result.push(groupNumber[input.group]);
}
groupNumber[input.group].values.push(input);
return groupNumber;
}, {});
Is reduce the correct function to be used here? Is there a more efficient approach?
Secondly, will reduce preserve the order in the result? If I am actually receiving the data with group 1 entries first, group 2 next, and so on, can I rely on result being ordered similarly?
Note that I only care about the order of the groups, not about the values inside the group.
Actually either by using reduce() or any other Array methods, the order will be always preserved as they will be executed from index 0 till the end of the array.
But reduce() is mainly used to accumulate the array elements into a single element, it's not the best method for doing such thing but it can be used as well.
Note that your actual code using reduce() isn't returning the right output.
In my opinion I think Array.map() method is better in this case, but it should be used in combination with Array.filter() to remove duplicate elements that will be kept with map():
var result = data.map(v => {
v.values = data.filter(e => e.group == v.group).map(x => x.value);
delete v.value;
return v;
}).filter(x => !x.values.some(e => !e));
Demo:
let data = [{
group: '1',
value: 'a'
}, {
group: '1',
value: 'b'
}, {
group: '2',
value: 'c'
}, {
group: '2',
value: 'd'
}];
var result = data.map(v => {
v.values = data.filter(e => e.group == v.group).map(x => x.value);
delete v.value;
return v;
}).filter(x => !x.values.some(e => !e));
console.log(result);
I would save my reply because we have a great explanation why your approach is great, because you have O(N) computational complexity (Thanks for the great comments to #CertainPerformance) and you iterate your array just one time.
Testing whether reduce method preserve order of object keys:
It looks like reduce method is not preserving order of keys. Here we see that keys are sorted in order how then iterated through source array myArray, however in Chrome browser this behavior is not reproducible(keys are sorted):
var myArray = [{letter: 'c'}, {letter:'e'}, {letter: 'e'}, {letter:'b'}, {letter: 'c'}, {letter:'a'}, {letter:'b'}, {letter:'a'}, {letter: 'd'}, {letter: 'd'}, {letter: 'd'}, {letter: 'd'}];
var myOrderedKeys = myArray.reduce((a, {letter}) => {
a[letter] = a[letter] || letter;
a[letter] = letter;
return a;
}, {})
console.log(myOrderedKeys);
Another example where we have more than one letter:
let notSimpleLetters = [{letter: 'ce'}, {letter:'ec'}, {letter: 'ec'}, {letter:'bw'}, {letter: 'ce'}, {letter:'aw'}, {letter:'ba'}, {letter:'aa'},
{letter: 'df'}, {letter: 'cb'}, {letter: 'dc'}, {letter: 'da'}];
let notSimpleKeys = notSimpleLetters.reduce((a, {letter}) => {
a[letter] = a[letter] || letter;
a[letter] = letter;
return a;
}, {})
console.log(notSimpleKeys);
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);