How can I convert an Array into a Object? [duplicate] - javascript

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 3 years ago.
I have the following array:
['2020-01-16', '2020-01-17', '2020-01-18']
I need to turn the array above into an object like this:
{
'2020-01-16': {selected: true, marked: true, selectedColor: 'blue'},
'2020-01-17': {selected: true, marked: true, selectedColor: 'blue'},
'2020-01-18': {selected: true, marked: true, selectedColor: 'blue'},
}
Is there a way I can do this?

Sure, using Array.reduce(), this is a pretty straightforward thing. The accumulator in the reduce function is simply an empty object, and each iteration through reduce, we create a new property with that array item's value as the property name, and define the object literal as the value of that property.
Hope this helps!
const myArray = ['2020-01-16', '2020-01-17', '2020-01-18'];
const myObject = myArray.reduce( (obj, item) => {
obj[item] = {selected: true, marked: true, selectedColor: 'blue'};
return obj;
}, {});
console.log(JSON.stringify(myObject) );

I would use reduce to handle this (documentation on reduce):
var arr = ['2020-01-16', '2020-01-17', '2020-01-18'];
arr.reduce(function(accumulator, val){
accumulator[val] = {selected: true, marked: true, selectedColor: 'blue'};
return accumulator;
}, {});
This will build out your object as it loops over the array. I like using reduce over forEach, when I can

Use .forEach() to iterate over all of them and build your object out.
var myKeys = ['2020-01-16', '2020-01-17', '2020-01-18'];
var myObject = {};
myKeys.forEach((key) => myObject[key] = {
selected: true,
marked: true,
selectedColor: 'blue'
});
console.log(myObject);
You'll likely need to change the logic as far as the specific data you're plugging in (for selected, marked, selectedColor), but this is the simplest approach generally.

Related

How to turn multiple arrays of booleans to single array of booleans

I am finding it hard to work out the best way to take multiple arrays of the same length and merge them into a single array of true values. So if true is in the index position, the new array should have true, else just leave false.
const array1 = [true, true, false, false, true]
const array = [true, false, false, true, false]
Output is:
[true, true, false, true, true]
You can do this with map. It will generate new array for you. Inside map there are certain arguments you can pass current value and iteration using which you will get the data from second array and then put an OR || condition to get the expected output.
const array1 = [true, true, false, false, true];
const array = [true, false, false, true, false];
const output = array1.map((val,i)=>val || array[i]);
console.log(output);
You can use map() and check any of e OR array[i] is true, here e belong to each element of array1 and array[i] means each element of array respectively.Finally, it will make a newArray after conditional checking inside the map function.
const array1 = [true, true, false, false, true];
const array = [true, false, false, true, false];
var newArray = array1.map((e, i) => Boolean(e | array[i]));
console.log(newArray)

How to convert object to array only if its each value is true

I have selectedSizeList on my state.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false}
How do I convert my selectedSizeList to this array?
[2, 3, 4]
Do I have better algorithm than this one? (I assume my solution is not correct)
let array = [];
Objects.keys(selectedSizeList).maps((item) => {
if(item.value) array.push(item.value)
);
return array;
You can use array#filter to filter out all keys with true value.
const selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
const result = Object
.keys(selectedSizeList)
.filter(k => selectedSizeList[k])
.map(Number);
console.log(result);
First of all get the array keys using Object.keys() and then use filter() to filter only the true values like this.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var keys = Object.keys(selectedSizeList);
var filtered = keys.filter(function(key) {
return selectedSizeList[key]
});
console.log(filtered);
Try this (O(n) solution):
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var arr = [];
for (var key in selectedSizeList) {
if(selectedSizeList[key]){
arr.push(key);
}
}
console.log(arr);
You could use Object.keys() to return an`array that you can then use Array.prototype.filter() on to return a new array.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
let array = Object.keys(selectedSizeList).filter((item) => {
if(selectedSizeList[item]) return item;
});
//returns [2,3,4]
You can use Object.keys to get an array that you can then filter for values equal to true which will return an array of numbers as a string. You can then map through the array using Number to convert the number strings to numbers which may or may not be necessary depending on what you plan to do with this result. I put this into a function that you can re-use or at least not have your object hard coded with.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
// Re-usable function not tied to specific object
const filterForTrueValue = (obj) => Object
.keys(obj)
.filter(k => obj[k])
.map(Number);
console.log(filterForTrueValue(selectedSizeList));

Set all Object keys to false

Lets say I have an object
filter: {
"ID": false,
"Name": true,
"Role": false,
"Sector": true,
"Code": false
}
I want to set all keys to false (to reset them). What's the best way to do this, I'd like to avoid looping with foreach and stuff. Any neat one liner?
Well here's a one-liner with vanilla JS:
Object.keys(filter).forEach(v => filter[v] = false)
It does use an implicit loop with the .forEach() method, but you'd have to loop one way or another (unless you reset by replacing the whole object with a hardcoded default object literal).
Using lodash, mapValues is a graceful, loop-free way:
filter = {
"ID": false,
"Name": true,
"Role": false,
"Sector": true,
"Code": false
};
filter = _.mapValues(filter, () => false);
If you want to do this with Underscore.js, there is an equivalent, but with a slightly different name:
filter = _.mapObject(filter, () => false);
In either case, the value of filter will be set to:
{ ID: false,
Name: false,
Role: false,
Sector: false,
Code: false }
If you're not using ES6, here is its ES5 counterpart.
Object.keys(filter).forEach(function(key, value) {
return filter[key] = false;
})
If you don't want to modify the array, here's an ES6 alternative that returns a new one:
Object.fromEntries(Object.keys(filter).map((key) => [key, false]))
Explanation:
Object.keys returns the object's keys:
Object.keys({ a: 1, b: 2 }) // returns ["a", "b"]
Then we map the result ["a", "b"] to [key, false]:
["a", "b"].map((key) => [key, false]) // returns [['a', false], ['b', false]]
And finally we call Object.fromEntries that maps an array of arrays with the form [key, value] to an Object:
Object.fromEntries([['a', false], ['b', false]]) // returns { a: false, b: false }
A small line of code compatible with all browsers:
for(var i in your_object) your_object[i] = false;
With ES6 features one-liner without mutation:
{
...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
}
hasOwnProperty must be used
```
for(var i in your_object) {
if (Object.hasOwnProperty.call(your_object, i)) {
your_object[i] = false;
}
}
```
In case you are dealing with 'scope' variables, this might be a better solution.
Object.keys(filter).reduce(function(accObj, parseObj) {
accObj[parseObj] = false;
return accObj;
}, {});
Here's what i would call a neat one-liner solution:
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
Demo:
const filter = {
'ID': false,
'Name': true,
'Role': false,
'Sector': true,
'Code': false
};
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
console.log(filtered);
We are basically converting the object into an array using Object.assign() so we can use the map() fucntion on it to set each propety value to false, then we convert the array back to an object using the Object.assign() with the spread operator :)

Getting object property value

My array is the following:
let arr = [
{type: "Benzine", active: false},
{type: "Diesel", active: false},
{type: "Electricity", active: false}
]
And I have a function where I want to get value of the property active of that array:
function isChecked(filterName) {
return arr.filter(f => f.type === filterName).map(c => c.active)[0];
}
That works fine, with [0] at the end. Is there any way to show the active property value without [0] at the end?
No, as long as you use filter, there's not.
The [0] is used to get the first result from that filter.
Since you're just returning the value of active, you could use Array.prototype.some, instead:
let arr = [
{type: "Benzine", active: false},
{type: "Diesel", active: false},
{type: "Electricity", active: true}
];
function isChecked(filterName){
// Is there an element in the array that matches the filter AND is active?
return arr.some(f => f.type === filterName && f.active);
}
console.log("Diesel:", isChecked("Diesel"));
console.log("Electricity:", isChecked("Electricity"));
Instead of using filter, you can use find to get the first matching element of an array.
function isChecked(filterName) {
var elem = arr.find(f => f.type === filterName);
return elem ? elem.active : false;
}

How to convert an object into an array?

I have array of object and I want to change into array an remove object.
My object is like:
[{ABC: "ELEMENT1", MAX: 2, MIN: "Yes"}, {ABC: "ELEMENT2", MAX: 1, MIN: "Yes"}]
and I want result like array with index:
[{"ELEMENT1",2,"Yes"},{"ELEMENT2",2,"Yes}]
Use Array#map over Object.keys(obj)
The Object.keys() method returns an array of a given object's own enumerable properties.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var ip = {
STU: "Study1",
SUB: 2,
EXL: "Yes"
};
var op = Object.keys(ip).map(function(key) {
return ip[key];
});
console.log(op);
To iterate Array-of-Objects
var ip = [{
STU: "Study1",
SUB: 2,
EXL: "Yes"
}, {
STU: "Study2",
SUB: 4,
EXL: "No"
}];
var op = ip.map(function(item) {
return Object.keys(item).map(function(key) {
return item[key];
});
});
console.log(op);
That would be:
var array = Object.keys(obj).map(key => obj[key]);
However, order is not guaranteed for Object.keys as it works like a for-in loop, whose order of traversal is arbitrary. You may not get ["Study1",2,"Yes"] in that exact order. If you want to guarantee order, you must use an array containing the order of the keys and extract them from your object in that order.
var keyArray = ['STU', 'SUB', 'EXL'];
var array = keyArray.map(key => obj[key]);

Categories

Resources