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)
Related
I would like to use spread syntax to copy properties from several unknown objects into one object. Something like this:
var array = [{a:0}, {b:1}, {c:2}]; // This array could hold any number of objects
// This function should take the objects in the array and use spread syntax to create a new object.
function merge(arr) { /* Code I wish I knew */ } // returns an object
var combo = merge(array);
console.log(combo); // {a:0, b:1, c:2}
I am aware of Object.assign. My reason for asking this question is just to see if this sort of thing can be done with spread syntax. Additionally, I'm concerned with V8's Hidden Classes. From what I understand, modifying an object after it is instantiated negatively impacts the performance of the Hidden Class. I've read that Spread doesn't have this issue, possibly because it instantiates the object with all of the properties of the other objects.
You can use a combination of Array.reduce with Object.assign:
var array = [{a:0}, {b:1}, {c:2}];
function merge(arr) {
return array.reduce((x,y) => Object.assign(x, y))
//
// per the comments, if we don't want to mutate the original object we can do instead:
// return array.reduce((x,y) => Object.assign(x, y), {})
}
var combo = merge(array);
console.log(combo);
You can use Array#reduce to iterate the array and merge the children into one object:
var array = [{a:0}, {b:1}, {c:2}];
function merge(arr) {
return arr.reduce((acc, cur) => ({ ...acc, ...cur }));
}
var combo = merge(array);
console.log(combo);
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);
My data structure object is a Map with the following structure:
{
"2018-09-25":[0,1,2,0,8],
"2018-10-17":[0,2,0,0,0],
"2018-10-26":[0,2,1,0,0],
"2018-10-29":[0,2,2,1,0],
"2018-10-31":[0,3,2,1,0],
"2018-11-01":[0,3,3,1,0],
"2018-11-02":[0,4,4,1,0]
}
I use JSON.stringify and then JSON.parse. However, I would need the elements to be somehow named so that I can reference them (e.g. when drawing a chart).
I tried the following but I get NaN as a value.
data = Object.keys(data).map(function (k) {
return {date: new Date(k), value: +data[k]};
});
I would like to have something like this:
Key: "2018-09-25"
1:0
2:1
3:2
4:0
5:8
Since you are using map() it looks like you want an array as a final result. But, since the array will be a different size, map() doesn't really work. You can use reduce to flatten out the inner arrays into one big array:
let o = {"2018-09-25":[0,1,2,0,8],
"2018-10-17":[0,2,0,0,0],
"2018-10-26":[0,2,1,0,0],
"2018-10-29":[0,2,2,1,0],
"2018-10-31":[0,3,2,1,0],
"2018-11-01":[0,3,3,1,0],
"2018-11-02":[0,4,4,1,0]
}
let newAr = Object.entries(o).reduce((arr, [key, values]) => {
return arr.concat(values.map(n => ({date: new Date(key), value: n})))
}, [])
console.log(newAr)
Is that what you're after?
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);
I want to use lodash to convert an object like this:
var a = {1:'a', 3:'b', 2:'c'};
into a sorted array of values based on the keys of the object like:
var result = ['a','c','b'];
I know I can do this:
var keyRef = Object.keys(a).sort();
var result = keyRef.map(v => a[v]);
But is this way optimized - is there any function in lodash which is more optimized for this??
With plain Javascript, you could use Object.values and take this array as sorted result, because if the keys of the object could be read as 32 bit integer numbers, Javascript use them in numerical order.
Source:
The traversal order of object properties in ES6
var object = { 1: 'a', 3: 'b', 2: 'c' },
values = Object.values(object);
console.log(values);
Using lodash,
const o = {1:'a', 3:'b', 2:'c'};
const res = _.sortBy(o, (a, b) => b);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
Lodash has the _.values(obj) function. However it is noted that the result ordering is not guaranteed. However, as #Nina pointed out, if you stick to ints as the keys, the ordering should be consistent (unless lodash is doing something weird).