Can I create an Array from an Object just in one line? I don't want all the values object, just a selection:
const myObject = { a: 'foo', b: 'bar', c:'yep' }
const { a, c } = myObject
const myArray = Array.of(a, c)
console.log(myArray)
Could I use destructuring in some way inside the Array.of parameter?
Why not just :
const myObject = { a: 'foo', b: 'bar', c:'yep' };
let arr = Array.of(myObject.a, myObject.c);
console.log(arr);
Related
From an object like this:
{a:1, b: 2, c: 3}
I would like to turn into
['a', 'b', 'b', 'c', 'c', 'c']
Where the key is the string and the value is the number of copies, order doesn't matter.
What's the best way to do this?
I was thinking about using array.fill but not sure if that's actually easier than just iterating and push.
Edit: Currently this:
const arr = []
_.each(obj, function (v, k) {
_.times(v, function () {
arr.push(k)
})
})
You could flatMap the Object.entries and fill an array of each size.
const obj = { a: 1, b: 2, c: 3 };
const result = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));
console.log(result)
or with Lodash
const obj = { a: 1, b: 2, c: 3 };
const arr = _.flatMap(obj, (v,k) => Array(v).fill(k))
console.log(arr);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>
But there's nothing like a simple loop
const obj = { a: 1, b: 2, c: 3 };
const result = []
for (let [k, v] of Object.entries(obj)) {
while (v--) {
result.push(k)
}
}
console.log(result)
I would convert the object into an array of keys using Object.keys and then use a newly created empty results array, then map through the keys.
For each key I would add a fill array to the existing results.
Here's the ES6 solution to that (no extra libraries required)
const obj = { a: 1, b: 2, c: 3 };
let result = []
Object.keys(obj).forEach(key => {
result = [...result, ...new Array(obj[key]).fill(key)]
})
console.log(result)
You can use Object.entries and Array#reduce as follows:
const input = {a:1, b: 2, c: 3};
const output = Object.entries(input).reduce(
(prev, [key,value]) => prev.concat( Array(value).fill(key) ),
[]
);
console.log( output );
Or, using Array#push instead of Array#concat,
const input = {a:1, b: 2, c: 3};
const output = Object.entries(input).reduce(
(prev, [key,value]) => prev.push( ...Array(value).fill(key) ) && prev,
[]
);
console.log( output );
Or, using for loops,
const input = {a:1, b: 2, c: 3};
const output = [],
pairs = Object.entries(input);
for(let i = 0; i < pairs.length; i++) {
const [key, value] = pairs[i];
for(let j = 0; j < value; j++) {
output.push( key );
}
}
console.log( output );
how can i return an array of objects taking from array of again one more level array. I am using push.
is there any better way to achieve this
let a = [{b: [{c: "k"}]}]
let o = []
a.forEach(so => {so.b.forEach(obc => o.push(obc))})
console.log(o)
I'd use flatMap() instead:
const a = [{
b: [{
foo: 'foo'
}]
},
{
b: [{
c: "k"
},
{
bar: 'bar'
}
]
}
];
const o = a.flatMap(({ b }) => b);
console.log(o);
(but this is a relatively new method, so if you want to use it and still support older environments, be sure to include a polyfill)
Lacking that, you can also improve your existing code by using concat() with the inner array instead of iterating over each inner item:
const a = [{
b: [{
foo: 'foo'
}]
},
{
b: [{
c: "k"
},
{
bar: 'bar'
}
]
}
];
let o = [];
a.forEach(({ b }) => {
o = o.concat(b);
});
console.log(o);
Try
let a = [{b: [{c: "k"}]}]
let o =a[0].b
console.log(o)
I have the following objects like
obj1 = { key1: { a: 1}}
I want to merge the following object with the above
key1 = { b: 2}
I want to get the result as following by merging the key1 with the existing key in the first object.
{key1: {a: 1, b: 2}}
How can I do this using spread operator in javascript? Thanks in advance.
You can spread both existing and new object
Note: Using spread operator will only merge the enumerable properties.
const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
const res = {...obj1,key1:{...obj1.key1,...key1}};
console.log(res)
If you want to modify the original object then only change obj.key1
const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
obj1.key1 = {...obj1.key1,...key1}
console.log(obj1)
Just use the spread operator like so:
let obj1 = {
key1: {
a: 1
}
};
let key1 = {
b: 2
};
obj1.key1 = { ...obj1.key1, ...key1 };
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: auto; }
You could splead it into the wanted property.
var obj1 = { key1: { a: 1 } },
key1 = { b: 2 };
obj1.key1 = { ...obj1.key1, ...key1 };
console.log(obj1);
Try this:
let obj1 = { key1: { a: 1}}
let b = { b: 2}
let a = obj1.key1; //{a:1}
// merge using spread operator
let key1 = {...a, ...b}; //{a:1, b:2}
obj1.key1 = key1; //{"a":1,"b":2"}
console.log(obj1) //{ "key1":{"a":1,"b":2"}}
You should use Object.assign
var obj1 = { key1: { a: 1}};
var key1 = { b: 2};
Object.assign(obj1.key1, key1);
console.log(obj1)
Here is my code:
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
value[dealId] = array2.push(obj[property]);
}
console.log(value)
The output of this is
Object { 123: 3 }
But I want and this is what I was expecting.
Object { 123: [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}] }
Why am I getting 3 instead of an array? How to get the array?
Array.prototype.push returns the new length of the array, not the array itself. Your loop assigns the values 1, 2 and 3 to the same value[dealId].
Instead, you can move the assignment outside the loop:
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
Or you can simply use Object.values:
value[dealId] = Object.values(obj);
But note that this does not list inherited properties.
Why not build a new object with a single key and the given array as value?
For the object use a computed property name.
const
array = [{ a: 'abc', b: 'cd' }, { a: 'abc', b: 'xyz' }, { a: 'abc', b: 'mno' }],
key = 123,
object = { [key]: array };
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you need to add into aaray first then create the object
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value);
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value)
Assign your new obj property (id) the requested array:
let arr = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let newObj = {};
let id = 123;
newObj[id] = arr;
console.log(newObj);
Say I have an object like this:
object_1 = {
a: 10,
b: 5,
c: 15
};
Is there a quick way to create another object that only has the same keys, like?
object_2 = {
a: 0,
b: 0,
c: 0
}
I know Object.keys(object_1) gives me an array with the keys but I don't know how to assign them as keys in the new object.
object_2 = Object.assign({}, Object.keys(object_1))
If I could somehow invert that array that would work :D
You could use Object.assign with mapped objects and spread syntax ... and computed property names.
var object1 = { a: 10, b: 5, c: 15 },
object2 = Object.assign(...Object.keys(object1).map(k => ({ [k]: 0 })));
console.log(object2);
You can iterate the keys of the object with Array#reduce, and create a new object:
var object_1 = {
a: 10,
b: 5,
c: 15
};
var object_2 = Object.keys(object_1).reduce((o, k) => (o[k] = 0, o), {});
console.log(object_2);
You can use .reduce as above or forEach to create a new object with the same keys and initialized values like below (This is without arrow function and other spread operator related to ES6)
var object_2 = {};
object_1 = {
a: 10,
b: 5,
c: 15
};
Object.keys(object_1).forEach( function(x){ object_2[x] = 0});
console.log(object_2);