Key, Value mapping in Object Literals - javascript

I tripped over a javascript question
Initially, response from HTTP was like [...{67,90},{23,40}], Now in order to view this detail in pie chart, i had to convert it into [{x:67, y: 90}, {x:23, y:40}], but now i want this pie data to again look like [{67,90},{23,40}].
For Example:
g = [{x: 67, y:90}, {x: 23, y:40}]
I tried few things like :
1.
Object.keys(pieData).map((item) => {
return {
item.x, item.y
}
})
2.
Object.key(Object.entries(g))
Required result is:
g=[{67,90}, {23,40}]
Any help would be appreciated.
Second part of the above question is '67', '23' are actually indexes. Can we convert one of the values in index number of the array....?

If you want the x as the key and the y as the value this is what you're looking for.
var g = [{x: 67, y:90}, {x: 23, y:40}];
var result = g.map(item => ({[item.x]:item.y}));
console.log(result);

Your expected output is wrong because it contains object without key:value pairs. You should return array of arrays. Use map() and return an array containing both properties.
let g = [{x: 67, y:90}, {x: 23, y:40}]
let res = g.map(({x,y}) => [x,y]);
console.log(res)

Notice that the result g = [{67, 90}, {23, 40}] that you want is not valid javascript
I think that what you want is an array of objects [{67: 90}, {23: 40}] with the x as key and the y as value
To get that, as you post in your question you can use Array.prototype.map()
Code:
const g = [{x: 67, y:90}, {x: 23, y:40}];
const result = g.map(o => ({ [o.x]: o.y }));
console.log(result);

Related

Create object with total value from associated string array and integer array

I have a string array of product IDs, like this:
["A", "A", "B", "A"]
And another integer array of prices, like this:
[30, 50, 10, 40]
What would be the best way to produce a Javascript object with the unique item and its total cost, as the order of the integers are the prices associated with the same order of product numbers, so ideally it would return an object like this i.e.
{"A": 120, "B": 10}
Thank you!
I am relatively new to Javascript and SQL but I have tried using a foreach statement which I used successfully to produce a unique count of the item when I extract just that column into an array but not the problem as described above.
Simple reduce loop
const productIds = ["A", "A", "B", "A"];
const prices = [30, 50, 10, 40]
const totals = productIds.reduce((acc, key, index) => {
acc[key] = (acc[key] || 0) + prices[index];
return acc;
}, {});
console.log(totals);
Assuming that both the arrays are of equal lengths, by using a linear search with a map to store and add the count would be the correct approach in this case:
function getSummation(productIds, prices) {
const store = {};
for (let i=0; i < productIds.length; i++) {
if (!store[productIds[i]])
store[productIds[i]] = 0;
store[productIds[i]] += prices[i];
}
return store;
}
Shorter version using comma operator
const products = ["A", "A", "B", "A"];
const prices = [30, 50, 10, 40];
const obj = products
.reduce((acc,cur,i) => (acc[cur] = (acc[cur] ??= 0) + prices[i], acc),{});
console.log(obj)
const keys = ["A", "A", "B", "A"];
const values = [30, 50, 10, 40];
const result = keys.reduce((t, v, i) => ({...t, [v]: (t[v] || 0) + values[i]}), {});
console.log(result);

What is the most optimal way to convert Array to Object Array including array entries as object keys?

Consider the following two arrays:
var array=[
["2021-06-11", 100, 80, 70],
["2021-06-12", 101, 81, 71],
["2021-06-13", 102, 82, 72],
["2021-06-14", 103, 83, 73]]
var keyNames = ["date","a","b","c"];
Target:
var newArray = [{date:"2021-06-11",a:100,b:80,c:70},
{date:"2021-06-12",a:101,b:81,c:71},
{date:"2021-06-13",a:102,b:82,c:72},
{date:"2021-06-14",a:103,b:83,c:73}]
What is the most optimal way to achieve this? can be done with forEach() or a combination with reduce / map prototyping?
I've tried with var obj = Object.assign({}, array)
but the result was index as keys
Any help will be appreciated!
Thank you for your time!
Can be done using map and forEach.
let newArray = array.map((x) =>{ //map to convert the first array
let newObj = {};
let index =0;
keyNames.forEach((y) =>{ //forEach to loop through keynames
newObj[y] = x[index++];
});
return newObj;
});

Javascript: How to make array from object with key value pairs as strings?

I have an object, from which an array has to be made, where key + value pairs are converted to strings.
var obj = {'x': 1, 'y': 2, 'z':3};
I have tried to convert the content to strings:
var joined = Object.entries(obj ).join(' ');
"x,1 y,2 z,3"
and to an array of arrays
var entries = Object.entries(obj);
But it is not exactly what I need
My ideal result is
var arrayFromObject = ['x 1', 'y 2', 'z 3'];
I can probably flatten the array of arrays but maybe there is a better solution?
You can get the desired output using .map(), .join() and Object.entries():
Get an array of [key, value] pairs of a given object's properties using Object.entries().
Iterate using .map() over the array values returned in first step and use .join() to get the string in desired format.
const obj = {'x': 1, 'y': 2, 'z': 3};
const array = Object.entries(obj).map(a => a.join(' '));
console.log(array);
If you know you have a KVP set, you can do something like
const obj = {'x': 1, 'y': 2, 'z':3};
const result = Object.entries(obj).map(entry => `${entry[0]} ${entry[1]}`);
//(3) ["x 1", "y 2", "z 3"]
Object.keys(obj).map(x => `${x} ${obj[x]}`)
Explanation
Object.keys(obj) returns ["x", "y", "z"] and map then maps every key to a template literal ${x} ${obj[x]} where obj[x] is the value (y is mapped to y 2)
You can use for loop for your desired output, you could've used map but it creates performance issues if the list is large.
let obj = { x: 1, y: 2, z: 3 };
let outputArray = [];
for (let i = 0; i < Object.keys(obj).length; i++) {
outputArray.push(Object.keys(obj)[i]+' '+Object.values(obj)[i]);
}
console.log(outputArray);
const obj = {'x': 1, 'y': 2, 'z':3};
const array = Object.entries(obj).map(a => a.join(' '));
console.log(array);

Create x y array with already created array of values

I need to create a graph with some data from an API and it has to be in the following format:
[
{
x: '2020-05-31',
y: 120
}
{
x: '2020-05-30',
y: 140
}
{
x: '2020-05-29',
y: 160
}
]
I currently can grab some data from the API in the form of 2 arrays and I'm wondering how can I get this data in a format like the above. Example arrays of data below.
[120, 140, 160]
and
["2020-05-31", "2020-05-30", "2020-05-29"]
How do I get those values into a 2 dimensional array of objects?
You can make use of the index parameter in Array#map.
const vals = [120, 140, 160],
dates = ["2020-05-31", "2020-05-30", "2020-05-29"];
const res = dates.map((x, i) => ({ x, y: vals[i] }));
console.log(res);
Both solutions assume the first array is called xArr and the second array is called yArr
Solution with a for loop:
const newArray = [];
for(let i = 0; i<xArr.length; i++){
newArray.push({
x:xArr[i],
y:yArr[i]
}
}
Solution with a map:
const newArray = xArr.map((x, i) => ({x,y:yArr[i]}));

javascript ignore string and decimal point number in an array

please i have an array [ 45, 66, 90, 'bye', 100.5 ]
and I want to write a javascript function to ignore the 'bye' and also the ".5" and get a return array of [ 45, 66, 90, 100 ] as my output but I don't know how to go about it I'm new to javascript. this is what I tried
var filterFloat = function(value) {
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('100.5'))
You can use reduce. You can use Math.floor to round down the number.
var arr = [ 45, 66, 90, 'bye', 100.5 ];
var result = arr.reduce((c,v)=>{
if ( !isNaN( v ) ) c.push( Math.floor( v ) );
return c;
},[]);
console.log( result );
Doc: .reduce()
You can follow these steps:
Parse the value in array to convert it into integer. This will convert the values to integer
Then you can check whether the parsed value is actually a number or not using isNaN method. This will help you to detect the string values in the array which you can omit in your result set.
var arr = [ 45, 66, 90, 'bye', 100.5 ];
var result = [];
arr.map((item) => {
if(!isNaN(parseInt(item))){
result.push(parseInt(item));
}
});
console.log(result);
Here is a shorter answer:
var result = t.map(i => parseInt(i)).filter(Boolean)

Categories