Create object of objects from arrays [duplicate] - javascript

This question already has answers here:
How to combine two arrays into an array of objects? [duplicate]
(2 answers)
Closed 7 months ago.
I have two arrays in JavaScript:
a = [2, 5, 8, 10, 12, 15]
and
b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]
I want to turn this into an object of objects, like so:
ts = {
{
value: 2,
time: "2022-01-01"
},
{
value: 5,
time: "2022-01-02"
},
{
value: 8,
time: "2022-01-03"
},
{
value: 10,
time: "2022-01-04"
},
{
value: 12,
time: "2022-01-05"
},
{
value: 15,
time: "2022-01-06"
}
}
I have looked at the forEach method and the reduce method, e.g. from https://bobbyhadz.com/blog/javascript-create-object-from-two-arrays , but I am struggling. Edit: my attempt was along the lines of:
const ts = {};
a.forEach((a_value, index) => {
ts.value[index] = a_value[index];
});

A simple for loop will work if both lists are the same size.
let a = [2, 5, 8, 10, 12, 15]
let b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]
let ts = []
for (let idx in a) {
ts.push({value: a[idx],
time: b[idx]})
}
console.log(ts)

Related

Find minimum in array of dictionaries? [duplicate]

This question already has answers here:
Finding the max value of an attribute in an array of objects
(21 answers)
Compare JavaScript Array of Objects to Get Min / Max
(17 answers)
Closed 2 months ago.
I have something like :
var array = [
{'a':3,'b':4},
{'a':1,'b':8},
{'a':9,'b':7}]
What is an elegant one line to find the min/max of the key 'a' (max=9, min = 1) ?
I know it is simple but i couldn't find a one line solution only loops.
Logic
Create a simple array of the required nodes.
Use Math.max with the spread syntax to get the maximum.
const array = [{ a: 3, b: 4 },{ a: 1, b: 8 },{ a: 9, b: 7 }];
const max = Math.max(...array.map(({ a }) => a));
console.log(max);
Apply the same logic for min as well and use Math.min
const array = [{ a: 3, b: 4 },{ a: 1, b: 8 },{ a: 9, b: 7 }];
const nodes = array.map(({ a }) => a);
const maxMin = { max: Math.max(...nodes), min: Math.min(...nodes)};
console.log(maxMin);
you can do something like this
var array = [
{ a: 3, b: 4 },
{ a: 1, b: 8 },
{ a: 9, b: 7 },
];
const arrayA = array.map((v) => v.a);
const maxA = Math.max(...arrayA);
const minA = Math.min(...arrayA);
console.log({ minA, maxA });
Tried to keep it in 1 line.
var array = [
{ a: 3, b: 4 },
{ a: 1, b: 8 },
{ a: 9, b: 7 },
];
const result = {
min: Math.min(...array.map((x) => x.a)),
max: Math.max(...array.map((x) => x.a)),
};
console.log(result);

Combine results from array of objects based on key in nested array of objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have array of objects where I want to filter and combine results based on specific id. This is example:
[
{
id: 1,
items: [
{
id: 10,
values: [11],
},
{
id: 20,
values: [13, 14, 15],
},
],
},
{
id: 2,
items: [
{
id: 10,
values: [12],
},
{
id: 20,
values: [13, 15],
},
],
},
];
And this is expected result:
[
{
id: 10,
values: [11, 12],
},
{
id: 20,
values: [13, 14, 15],
},
];
I also need to filter duplicates. Thanks
Note: What if I want this result?
[
{
// here I want value for id 10 (it will be always one number)
value: 11,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 14, 15],
},
{
// here I want value for id 10 (it will be always one number)
value: 12,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 15],
},
];
I tried the same approach with Map, but without success. Basically I want to combine values based on ids.
You could do with Array.flatMap to filter all items in single array.
Then recreate the array with Array.reduce and push the value based on id into new value object
And use Array.filter ignore the duplicate values on array
Object.values return only the value of object in array format
Older
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
const res = Object.values(arr.flatMap(({items})=> items)
.reduce((acc,{id,values})=>{
acc[id] = acc[id] ?? {id,values:[]};
//check the object exist or not
let newArr = acc[id]['values'].concat(values);
let valArr = newArr.filter((v,i)=>newArr.indexOf(v) === i)
//remove the duplicates
acc[id]['values'] = valArr
return acc
},{}))
console.log(res)
Updated
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
function filterMethod(arr,value,values){
return arr.map(({items})=> ({
value:detector(items,value)[0],
values:detector(items,values)
}))
}
function detector(items,idVal){
let ind = items.findIndex(({id})=> id === idVal);
return ind > -1 ? items[ind]['values'] : ['']
}
console.log(filterMethod(arr,10,20))

How can I transform the Object in this Array of Objects? [duplicate]

This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Closed 1 year ago.
Given this array of objects:
arrayBefore: [
{
a: "string1",
b: 10,
},
{
a: "string2",
b: 20,
},
]
how can one change the keys using JavaScript for the end result of:
arrayAfter: [
{
x: "string1",
y: 10,
},
{
x: "string2",
y: 20,
},
]
You can use Array.prototype.map to transform the objects.
const arrayBefore = [{
a: "string1",
b: 10,
},
{
a: "string2",
b: 20,
},
]
const arrayAfter = arrayBefore.map((item) => ({
x: item.a,
y: item.b,
}))
console.log(arrayAfter)

Manipulate object property of an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have an array of objects with some property. I wanted to do some math on the object property, and expect to return an array as well.
I've tried, doesn't seems to work.
array.map(el => {
el.count * 2;
return el
})
array = [{
count: 4,
string: 'randomstring'
}, {
count: 9,
string: 'randomstring'
}, {
count: 7,
string: 'randomstring'
}, {
count: 12,
string: 'randomstring'
}]
Expected
array = [{
count: 8,
string: 'randomstring'
}, {
count: 18,
string: 'randomstring'
}, {
count: 14,
string: 'randomstring'
}, {
count: 24,
string: 'randomstring'
}]
el.count * 2; will not change the value of el.count You could assign it to it like
el.count = el.count * 2;
But this will create another problem. It will change the original data. So better to return a new object with modified count property using Spread Operator
let array = [{ count: 4, string: 'randomstring' }, { count: 9, string: 'randomstring' }, { count: 7, string: 'randomstring' }, { count: 12, string: 'randomstring' }]
let res = array.map(el => ({...el,count:el.count*2}));
console.log(res);
You can also you Object.assign()
let res = array.map(el => Object.assign({count:el.count*2}));
You could map independent objects without mutating the original array.
newArray = array.map(o => Object.assign({}, o, { count: o.count * 2 }));
The same with spreading the object.
newArray = array.map(o => ({ ...o, count: o.count * 2 }));
Without explicitly mutating object's value (that's why we use map, filter and reduce in the first place):
array.map(({ count, string }) => (
{ count: count * 2, string }
));
try
array.map(e=>(e.count*=2,e))
let array = [
{ count: 4, string: 'randomstring' },
{ count: 9, string: 'randomstring' },
{ count: 7, string: 'randomstring' },
{ count: 12, string: 'randomstring' }
];
let r = array.map(e=>(e.count*=2,e))
console.log(r);

Best way to returns keys from object in an array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I have an array of objects like this:
var myArray = [{
key: 2,
value: 10,
},
{
key: 5,
value: 4,
},
{
key: 3,
value: 8,
},
{
key: 12,
value: 4,
}];
How is the most elegant way to convert this array in other just with the key numbers: [2,5,3,12]?
Use array.map
var myArray = [{
key: 2,
value: 10,
},
{
key: 5,
value: 4,
},
{
key: 3,
value: 8,
},
{
key: 12,
value: 4,
}];
console.log(myArray.map(a => a.key));
Use .map:
const myKeys = myArray.map(i => i.key);

Categories

Resources