How to get value from index property in javascript? - javascript

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);

Related

How to get all values of a specific key in array of objects?

I have array of objects like this
const object1 = {
a: 'somestring',
b: 42,
c: false
};
const object2 = {
a: 'somestring2',
b: 42,
c: false
};
const object3 = {
a: 'somestring3',
b: 42,
c: false
};
const arr = [object1,object2,object3]
i want to get all the values of 'a' key.
so result be
['somestring','somestring2','somestring3']
I tried Object.values() but it gets me all values of all keys, which is not the desired output.
Just use map() function:
const arr = [object1,object2,object3].map(({a}) => (a))
An example:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
const object2 = {
a: 'somestring2',
b: 42,
c: false
};
const object3 = {
a: 'somestring3',
b: 42,
c: false
};
const arr = [object1,object2,object3].map(({a}) => (a))
console.log(arr)
Have you tried const arr = [object1.a, object2.a, object3.a]? That might work

Best way to create an array from an object that has number of copies

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 to access and assign new value in array/object in lodash

I am looking for simple easy way to assign new value through lodash. See the blow example. I only want to reassign value of first element of object of first element of arr array.
const arr = [
{
a: 'apple',
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
const newArr = arr;
const ele = ._first(newArr);// picked first element
ele['a'] = 'dog';
this is what I expect to see
console.log(newArr);
// [
{
a: 'dog', //<--- updated
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
thank you ahead!
Why you cannot just use simple JS without lodash?
const arr = [
{
a: 'apple',
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
const newArr = arr;
newArr[0].a = 'dog'
console.log(arr)

How to merge with nested key in javascript spread operator?

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)

How to map more than one property from an array of objects [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
I have an array of Object as follows:
var obj = [
{a: 1, b: 5, c: 9},
{a: 2, b: 6, c: 10},
{a: 3, b: 7, c: 11},
{a: 4, b: 8, c: 12}
];
I know about how to get single object using Array.map() like this.
var result = obj.map(x=>x.a)
This will give me following result
[1, 2, 3, 4]
But I want result like follows:
[
{a: 1, b: 5},
{a: 2, b: 6},
{a: 3, b: 7},
{a: 4, b: 8}
]
In short, from an array of objects I want to select only a few fields (more than one).
How can I do that?
You can use .map() with Object Destructuring:
let data = [
{a:1,b:5,c:9}, {a:2,b:6,c:10},
{a:3,b:7,c:11}, {a:4,b:8,c:12}
];
let result = data.map(({ a, b }) => ({a, b}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If, as in your example, you want to exclude a particular property or few, you can use destructuring and use rest properties to create an object with only the properties you want:
var obj = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
const mapped = obj.map(({ c, ...rest }) => rest);
console.log(mapped);
If you want to include properties, simply extract them from the .map callback:
var obj = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
const mapped = obj.map(({ a, b }) => ({ a, b }));
console.log(mapped);
Use map():
var data = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let modified = data.map(obj => ({a: obj.a, b: obj.b}))
console.log(modified);
Or if you prefer destructuring:
var data = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let modified = data.map(({ a, b }) => ({a, b}));
console.log(modified);
var obj = [
{a: 1, b: 5, c: 9},
{a: 2, b: 6, c: 10},
{a: 3, b: 7, c: 11},
{a: 4, b: 8, c: 12}
];
var result = obj.map(e => ({a:e.a , b:e.b}));
console.log(result)
You can return a custom object with required properties using map()
var obj = [{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let op = obj.map(e => {
return { a:e.a, b: e.b };
})
console.log(op);
In your solution for producing [1,2,3,4], x.a isn’t some micro-syntax, it’s actually a full-fledged JavaScript expression. So you can just replace it with the JavaScript for creating a new object with the properties you want.
var result = obj.map(x=>{a: x.a, b: x.b});
... almost. The additional complication is that a { after a => is interpreted as the beginning of a function body, not the beginning of an object literal. You can avoid this by just wrapping the object literal in otherwise-noop parenthesis.
var result = obj.map(x=>({a: x.a, b: x.b}));
You can make your own custom function for this, and pass it a set of properties which you want to extract. :
var array = [{a:1,b:5,c:9}, {a:2,b:6,c:10}, {a:3,b:7,c:11}, {a:4,b:8,c:12} ];
function extractProperties(arr, properties){
return arr.map((obj)=> Object.keys(obj).reduce((acc,key)=>{
if(properties.has(key))
acc[key] = obj[key];
return acc;
},{}));
}
let set = new Set(["a","b"]);
let result = extractProperties(array, set);
console.log(result);
set.add("c");
console.log("**************result2**********")
let result2 = extractProperties(array, set);
console.log(result2);

Categories

Resources