This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Closed 5 years ago.
How can I transform values from an array to a new array?
I have an array like:
[
{ "amount" : 10, "date" : "2017-05-30" }...
]
which I want to "transform" into
[
{ x : 10, y: 2017-05-30 }
]
any help is appreciated...
You could map new objects with the new properties.
var array = [{ amount: 10, date: "2017-05-30" }],
newArray = array.map(a => ({ x: a.amount, y: a.date }));
console.log(newArray);
Using Array#map()
The callback function will create a new object with the 2 properties needed. You just have to keep the value of the current array
const array = [{ "amount" : 10, "date" : "2017-05-30" }];
let newArray = array.map(_=>({x:_.amount,y:_.date}));
console.log(newArray);
You can try using lodash map Lodash map
It will be something like:
const array2 = _.map(array1, (item) => { x: item.amount, y: item.date });
Related
This question already has answers here:
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Closed 5 months ago.
I Want to sum all price values of an array for duplicated elements in array... I have this array:
var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]]
And this is what I want:
var products = [["product_1", 10, "hamburger"],["product_2", 17, "cola"]]
Can any good soul help me?
I think you meant to write ........, ["product_1", 4, "hamburger"]].
You can use Object.values() and Array#reduce methods as in the following demo:
const
products = [
["product_1", 6, "hamburger"],
["product_2", 10, "cola"],
["product_2", 7, "cola"],
["product_1", 4, "hamburger"]
],
output = Object.values(
products.reduce(
(acc, [id, num, name]) =>
({ ...acc,
[id]: [id, (acc[id] && acc[id][1] || 0) + num, name]
}), {}
)
);
console.log(output);
This question already has answers here:
How to combine two arrays into an array of objects in javascript?
(2 answers)
Combine the values of two arrays into object
(5 answers)
How to create a JS object from arrays [duplicate]
(4 answers)
Closed 6 months ago.
Is there a nice way of transforming a flat javascript array into an array of objects?
An example would be to transform this array.
I'm stuck in trying to merge the two arrays and create an object with the values.
const dataSet = [
{
last_updated: 1662040601,
x: [
1660953600, 1661040000, 1661126400, 1661212800, 1661299200, 1661385600,
1661472000, 1661558400, 1661644800, 1661731200, 1661817600, 1661904000,
],
y: [
0.07, 0.062, 0.06, 0.0725, 0.075, 0.089, 0.0799, 0.1167, 0.089, 0.08,
0.077, 0.0639,
],
},
];
Into this:
const array = [
{ data: 1660953600, value: 0.07 },
{ data: 1661040000, value: 0.062 },
{ data: 1661126400, value: 0.06 },
{ data: 1661212800, value: 0.0725 },
];
My attempt:
const arri = dataSet.map((data) => ({
data: data.x.map((data) => data),
value: data.y,
}));
I hope it will help you..
const array = dataSet[0].x.map((x, i) => ({ data: x, value: dataSet[0].y[i] }));
What do you think about it ?
This question already has answers here:
Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`
(3 answers)
Closed 1 year ago.
I'm sorry if this is redundant with other posts but I currently have the following array:
let test = {1:100, 2:200, 3:300}
But I'd like to convert this to:
test = [
{id: 1, value: 100},
{id: 2, value: 200},
{id: 3, value: 300}
]
Any help appreciated - even just pointing me to posts that solve this question :)
You can use Object.entries to get an array of key, value pairs and then map that to an array of objects:
let test = {1:100, 2:200, 3:300};
let out = Object.entries(test).map(([k, v]) => ({ id : k, value: v }));
console.log(out);
Here's a version using keys and map:
var obj = {1:100,2:200,3:300}
var result = Object.keys(obj).map((key) => ({ id: key, value: obj[key]}));
console.log(result)
Using Object.entries() and some destructuring
let test = {1:100, 2:200, 3:300}
let res = Object.entries(test).map(([id, value]) => ({id, value}))
console.log(res)
This question already has answers here:
Most efficient method to groupby on an array of objects
(58 answers)
Closed 2 years ago.
I have this array of object i want to convert:
let ordNumbers = [
{"seq":1,"ordNumber":"221"},
{"seq":1,"ordNumber":"224"},
{"seq":2,"ordNumber":"221"}
]
to this format
let filteredOrders = [
{"seq":[1,2],"ordNumber":"221"},
{"seq":1,"ordNumber":"224"}
]
Based on the order numbers i want the above format
You mean something like this?
var ordNumbers = [
{
"seq": 1,
"ordNumber": "221"
},
{
"seq": 1,
"ordNumber": "224"
},
{
"seq": 2,
"ordNumber": "221"
}
]
// formatted as { ordNumber: [seq] }
var pairs = ordNumbers.reduce((acc, v) => {
acc[v.ordNumber] = (acc[v.ordNumber] || []).concat(v.seq);
return acc;
}, {});
// formatted as [{"seq": [seqs], "ordNumber": ordNumber}]
var res = Object.keys(pairs).map(v => ({
seq: pairs[v],
ordNumber: v
}));
console.log(res);
let ordNumbers = [
{"seq":1,"ordNumber":"221"},
{"seq":1,"ordNumber":"224"},
{"seq":2,"ordNumber":"221"}
]
let ordMap = {}
for (let el of ordNumbers) {
// if the ordNumber exists in the map then pushing el.seq to it's value else setting el.seq as
// the value
ordMap[el.ordNumber] = ordMap[el.ordNumber] ? [...ordMap[el.ordNumber], el.seq] : [el.seq]
}
const result = Object.keys(ordMap).map(val => ({seq: ordMap[val], ordNumber: val}));
console.log(result)
This question already has answers here:
Filter Array of Array for values inside nested array
(4 answers)
Only specific 'columns' from a 2d javascript array
(4 answers)
Closed 4 months ago.
I have these variables:
var arr = [
[ "name1", 2, "filter1" ],
[ "name2", 5, "filter2" ],
[ "name3", 8, "filter3" ],
[ "name4", 1, "filter2" ]
];
// This variable may have values: `"filter1"`, `"filter2"`, `"filter3"`.
var filter = "filter2";
How can I filter the array arr according to the filter variable values?
My example must return this:
[
[ "name2", 5 ],
[ "name4", 1 ]
]
Beside the filtering, you need to get only the first two elements of the inner arrays.
Array#filter returns the same elements in the array. For getting the wanted items without the filter item, you need to return either the first two objects, or filter the items with the given filter as well (proposal 2).
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array.filter(a => a[2] === filter).map(a => a.slice(0, 2));
console.log(result);
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array
.filter(a => a.some(v => v === filter))
.map(a => a.filter(v => v !== filter));
console.log(result);
By using filter method you can easily test what you want and only return the match elements
var arr = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'],['name3', 8, 'filter3'], ['name4', 1, 'filter2']];
var filter = 'filter2';
var result = arr.filter(function(res){
return res[2] == filter;
}).map(function(filtered){
return filtered.slice(0,2);
});
console.log(result);