Creating multiple keys inside javascript object with Array.map - javascript

What I am trying to accomplish is from an array, I want to map all of those values into one object. For example, if I have the following data below
const myKeys = ["prop_1", "prop_2", "prop_3"];
When I map over this array I would like to return an object with 3 properties from the array listed above. Something like this.
const myKeysObj = myKeys.map( key => {
// expected outcome {"prop_1" : "some_value", "prop_2": "some_value", "prop_3": "some_value"}
// actual outcome {key: "some_value"}
return {[key]: "some_value"}
})
What can I do to have all three of my props in my array to be properties for a each object returned?

It looks like you want to reduce the keys into an object, in which case reduce is more appropriate than .map:
const myKeys = ["prop_1", "prop_2", "prop_3"];
const output = myKeys.reduce((a, key) => {
a[key] = 'some_value';
return a;
}, {});
console.log(output);

Related

How to create multiple objects from array's value in JavaScript?

I have an array like this:
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
I want something like this:
const converted = [{from:2}, {to:1}, {opacity:12}]
What I am trying is:
const mappedData = data.map(({from,to,opacity}) => ({from:from},{to:to},{opacity:opacity}))
but this is not working.
So you can loop through the array and for each object we can get the keys of the objects in the array and use a map to transform them to our desired output, Then the output will return an array, but we can use flatMap which will flatten the arrays returned into a single array of objects!
Thanks pilchard for teaching about flatMap!
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
const arr = data.flatMap(x => Object.keys(x).map(data => ({[data]: x[data]})))
console.log(arr);

Retrieving values for each key in JS Object and pushing each set of values for each key to it's own array

I want to iterate through my key/value pairs and push all the values for each key into its own array. These arrays of values of each key should be pushed to a single output array.
I hope this explains what I'm trying to do:
Input: map = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
Output: output = [["hello","hey","howdy"],["Goodbye","Ciao"]]
This is what I have so far:
return Object.keys(map).reduce((output, key) => {
return output.push(map[key])
},[])
Any help on iterating through the values for each key and adding those values to an array within another output array would be greatly appreciated.
For background, this is part of a grouping anagrams problem so I'm populating my Map as follows from a provided array "str" of strings.
let map = {};
str.forEach(anagram => {
const sortedWord = anagram
.split("")
.sort()
.join("");
map[sortedWord] = map[sortedWord] || [];
map[sortedWord].push(anagram);
});
All you need is the built-in Object.values():
Object.values() returns an array whose elements are the enumerable property values found on the object.
const map = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]};
const output = Object.values(map);
console.log(output);
Using reduce the return pushs to 'output' no need to push yourself:
return Object.keys(map).reduce((output, key) => {
return map[key]
},[])
You could also use map:
return Object.keys(map).map((key) => {
return map[key]
})
Apart from the above two excellent answers, you may choose to use Object.entries(), which will return an array from the input object's [key, value] pair. From there, we can return only the value into the resulting array, giving you the expected result.
const input = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
const result = Object.entries(input).map(item => item[1]);
console.log(result);
However, do take note that Object.entries() is not supported by Internet Explorer browsers.
Alternatively, you may use the good old for..in statement to iterate through the enumerable properties of the object, followed by pushing the corresponding values to the resulting array.
const input = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
const result = []
for (const property in input) {
result.push(input[property]);
}
console.log(result);

React - convert object into array of objects with properties

I have the following object
"data":{
"name 1":"a",
"name 2":"b",
"name 3":"b",
},
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render compoents for each one passing in the both the name and data?
If you use a reduce function you can do the following to achieve your goal
Object.keys(data).reduce((array, key) => {
return [...array, {key: data[key]}]
}, [])
Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)

spread operator converting objects to array

I'm trying to convert a data structure like this:
data = {
0:{A:a},
1:{B:b},
2:{C:c},
}
into a structure like this:
[
{0:{A:a}},
{1:{B:b}},
{2:{C:c}},
]
Using the spread operator like this: [...data] returns any empty array.
I also tried [{...data}]
Is there a way to use the spread operator to get the desired result? Also, why doesn't this approach work?
"Is there a way to use the spread operator to get the desired result?" Short answer, no. (see below for alternate solution to what you're trying to accomplish)
"Also, why doesn't this approach work?"
It doesn't work because according to the MDN docs
"The Rest/Spread Properties for ECMAScript proposal (stage 3) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object."
Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.
Alternative solution:
You can do this fairly easily with Object.keys().map(). Object.keys() will get an array of the keys of the object, and Array.map() will map them into an array of the desired structure, like so:
var data = {
0:{A:"a"},
1:{B:"b"},
2:{C:"c"},
}
var result = Object.keys(data).map(function (key) {
return { [key]: data[key] };
});
console.log(result);
You can use Object.entries to get [key, value] pairs, and map them to an array of objects using computed property names:
const data = {
0:{A: 'a'},
1:{B: 'b'},
2:{C: 'c'}
};
const result = Object.entries(data).map(([key, value]) => ({ [key]: value }));
console.log(result);
I'm afraid you cant use to spread operator like in your example, however you can produce the desired output with reduce.
data = {
0:{A:'a'},
1:{B:'b'},
2:{C:'c'},
}
let resArr = Object.keys(data).reduce((arr, e) => {
arr.push({[e]: data[e]});
return arr;
}, []);
console.log(resArr);
let data = ['Uzbek sila', 'Hikmatbet', 'Aslamboi']
let spread = [...data]
console.log(spread)

Convert array of objects to plain object using Ramda

How can I convert an array of objects to a plain object?
Where each item of the array is an object with only one key:value pair and the key have an unknown name.
I have this
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas' }
]
let result = {}
const each = R.forEach((item) => {
const key = R.keys(item)[0]
result[key] = item[key]
})
return result
But I dislike that solution because the forEach is using a global variable result and I'm not sure how to avoid side effects here.
Ramda has a function built-in for this, mergeAll.
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
R.mergeAll(arrayOfObject);
//=> {"KEY_A": "asfas", "KEY_B": "asas"}
Since everybody is using ES6 already (const), there is a nice pure ES6 solution:
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas'}
];
Object.assign({}, ...arrayOfObject);
//=> {KEY_A: "asfas", KEY_B: "asas"}
Object.assing merges provided objects to the first one, ... is used to expand an array to the list of parameters.
Use reduce instead:
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
const each = R.reduce((acc,value) => {
const key = R.keys(value)[0];
acc[key] = value[key];
return acc;
},{},arrayOfObject);
Since your array is an array of objects, you could also just call merge inside a reduce:
const each2 = R.reduce((acc,value) => R.merge(value,acc),{},arrayOfObject);
Here is a jsbin with both examples:
http://jsbin.com/mifohakeru/edit?js,console,output

Categories