In array of objects turn object values into key/value pair - javascript

I am interested to use chartkick and so I need to convert JS object with the following format:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
To the following format:
var arrayOne = [{'01/01/2017': 200}, {'02/01/2017': 220},{'03/01/2017':250}]
Any help would be greatly appreciated.

Use Array.prototype.map():
const src = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}],
result = src.map(({date,value1}) => ({[date]: value1}))
console.log(result)
.as-console-wrapper{min-height:100%;}

You can try this
let sampleArray = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
let finalArray = sampleArray.map(data => ({[data.date]:data.value1}))
console.log(finalArray)
Output Will be
[{01/01/2017: 200},{02/01/2017: 220},{03/01/2017: 250}]

var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}];
var mappedArray = array.map(item => {
return {
[item.date]: item.value1
}
})
loop the array and map it to the new structure

Try this:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
let final_array = array.map(arr => {
return {[arr.date] : arr.value1};
})
console.log(final_array)

If you want to do it in a loop for each value1, value2, ...
var array = [{
date: '01/01/2017',
value1: 200,
value2: 300,
value3: 400
}, {
date: '02/01/2017',
value1: 220,
value2: 330,
value3: 430
}, {
date: '03/01/2017',
value1: 250,
value2: 330,
value3: 420
}]
const numberOfValues = 3;
for (let i = 1; i <= numberOfValues; i++) {
const mappedArray = array.map(x => {
const result = {};
result[x.date] = x["value" + i.toString()];
return result;
});
console.log(mappedArray);
}

Related

What is the best way to access key/values of a object array when I don't know them?

I have this array above and I need every property of it
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
How could I extract every single key/value of it, once in theory, I don't know any of them?
I have already tried using object.keys but it returns the indexes of my array.
This should work
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
// to iterate over each element in the arry
arr.forEach(a => {
// To Iterate over each key in the element object
Object.keys(a).forEach(k => {
// to print the value of the 'k' key
console.log(k + ' : ' + a[k]);
})
})
1) You can use flatMap and Object.keys to get keys from an array of objects.
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = arr.flatMap((o) => Object.keys(o));
console.log(result);
2) To find all values in an array
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const values = arr.flatMap((o) => Object.values(o));
console.log(values);
3) If you want to find out all keys and values in an object
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = {
keys: [],
values: [],
};
for (let obj of arr) {
Object.entries(obj).map(([k, v]) => {
result.keys.push(k);
result.values.push(v);
});
}
console.log(result);
If you want to collect all the keys and values of a nested array of objects, you can use Array.prototype.reduce and then collect the keys and values of the nested objects in separate nested arrays, using Object.keys() and Object.values() respectively:
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
const allKeysAndValues = arr.reduce((acc, cur) => {
acc.keys.push(...Object.keys(cur));
acc.values.push(...Object.values(cur));
return acc;
}, { keys: [], values: [] });
console.log(allKeysAndValues);
A one liner could be
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
console.log( arr.map( obj => Object.entries(obj)));

How to use one array as keys for another array?

I have these two arrays and I want to output it like this:
{
"PT": "100",
"ES": "400",
"FR": "550",
"CH": "200",
"BR": "400",
"DE": "500",
}
How can I do that? Probably its simple but I can't figure out how to do this, also I searched on stackoverflow and I didn't find anything like this..
This is a project in React, I don't know if that matter.
Thanks.
It looks like those are what we call parallel arrays: The element at index n of one array relates to the element at index n of the other.
That being the case, you can use a simple for loop and brackets property notation:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
console.log(result);
You can also use map with Object.fromEntries to create the object, but it's more complicated (though shorter) and involves temporary array objects:
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
console.log(result);
Side note: In your output, you've shown the values 100, 200, etc. as strings, but they're numbers in your input. If you want them to be strings, just convert them as you go, like this:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
// −−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−^
}
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
}
console.log(result);
You'll get people pointing you at reduce, but reduce is only useful when you're doing functional programming with predefined, reusable reducer functions. Otherwise, it's just an overcomplicated, error-prone loop where using an actual loop would be clearer and easier to get right.
In a comment you've asked:
What If I want it do be like this? [{ text: 'pt', value: 100, }, { text: 'es', value: 500, }] ?
To do that, you want to create an object for each entry in the array. You can create the array via map, and you can create an object using an object literal ({text: "PT", value: 100} and similar, but getting the values from the array):
const result = array1.map((text, index) => ({text: text, value: array2[index]}));
or using shorthand property notation for the text property:
const result = array1.map((text, index) => ({text, value: array2[index]}));
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = array1.map((text, index) => ({text, value: array2[index]}));
console.log(result);
I've left those text values in upper case, but if you want to make them lower case in the objects, use .toLocaleLowerCase() on them:
const result = array1.map((text: text.toLocaleLowerCase(), index) => ({text, value: array2[index]}));
const arr1 = [100, 200, 300]
const arr2 = ["PT", "AT", "CT"]
const obj = {}
arr1.forEach((item, index) => {
obj[arr2[index]] = item
})
console.log(obj)
You can use .forEach to loop through one array and then populate the object.
const keys = ["PT", "ES", "FR", "CH", "BR", "DE"]
const values = ["100","400", "550", "200", "400", "500"]
const myObj = {}
keys.forEach((key,i) => myObj[key] = values[i]);
console.log(myObj);
a = ['a', 'b', 'c']
b= [1, 2, 3]
c = a.reduce((acc, item, index) => {
acc[item] = b[index];
return acc
}, {})
// {a: 1, b: 2, c: 3}
You can do this in a very simple loop:
const arr1 = ['key', 'key2', 'key3'];
const arr2 = ['val', 'val2', 'val3'];
const obj = {};
for (let i = 0; i < arr1.length; i++) {
obj[arr1[i]] = arr2[i];
}
console.log(obj);
This will result in an object like this:
{
key: 'val',
key2: 'val2',
key3: 'val3'
}

How to convert array of objects to object made up of only values

I have [ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }, .... ]. I want to convert it to
{ value1: value2, value3: value4 }
Use Array#reduce to accumulate your object-data. Foreach object take from the values the first and add a new property with this name to the accumulated object with the value from the second object-value.
let array = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }];
let res = array.reduce((acc, cur) => {
values = Object.values(cur);
acc[values[0]] = values[1];
return acc;
}, {});
console.log(res);
Assuming the inner objects always have 2 keys:
const arr = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }]
const obj = {};
for (const innerObj of arr) {
const values = Object.values(innerObj);
obj[values[0]] = values[1];
}
console.log(obj) // { value1: 'value2', value3: 'value4' }
Note: you're question assumes an order for the keys in the inner objects, but that may not be guaranteed

How to calculate the sum of items in an array?

Suppose i have an array:
const items = [
{
"amount1": "100",
"amount2": "50",
"name": "ruud"
},
{
"amount1": "40",
"amount2": "60",
"name": "ted"
}
]
I want to get all amount1 and amount2 props totalled and result in:
[
{
"amount1": 140,
"amount2": 110
}
]
How can I do this?
Using Array.prototype.reduce() with Object.entries() and Array.prototype.forEach():
const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];
const sums = items.reduce((acc, item) => {
Object.entries(item).forEach(([k, v]) => acc[k] = (acc[k] || 0) + v);
return acc;
}, {});
console.log(sums);
To filter out non-number properties (but keep quoted number strings, as per the updated question):
const items = [{amount1: '100', amount2: '50', name: 'Ruud'}, {amount1: '40', amount2: '60', name: 'Ted'}];
const sums = items.reduce((acc, item) => {
Object.entries(item)
.filter(([_, v]) => !isNaN(v))
.forEach(([k, v]) => acc[k] = (acc[k] || 0) + Number(v));
return acc;
}, {});
console.log(sums);
const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];
function sum(data){
const keys = Object.keys(data[0])
let res = {}
for(key of keys)
res[key]=data.map(x=>x[key]).reduce((a,b)=>a+b);
return res
}
console.log(sum(items))
Here is an alternative, simple, and clean solution for this.
const items = [{amount1:100, amount2:50, name:"ruud"},{amount1:40,amount2:60,name:"ted"}]
let result = [{amount1:0,amount2:0}]
items.forEach(i=>{
result[0].amount1 += i.amount1
result[0].amount2 += i.amount2
})
console.log(result)
Above solutions are great. I included this if you don't want to use
Array.prototype.reduce(). This will work even if you have other properties which are not "numbers"
const items = [{amount1: 100, amount2: 50, name: 'Ruud'}, {amount1: 40, amount2: 60, name: 'Ted'}];
var result = {};
items.forEach(function(eachItem){
for(var prop in eachItem){
if(typeof eachItem[prop] === "number"){
result[prop] = result[prop] ? result[prop] + eachItem[prop] : eachItem[prop];
}
}
});
result = [result];
console.log(result);
You can use reduce().
Use the reduce() method on the array items
Set the accumulator(ac) as an empty object i.e {}
During each iteration through the objects create a for..in loop to iterate through all keys of object.
Check if the typeof value of key is "number" then add it otherwise don't
const items = [{amount1:100, amount2:50, name:"ruud"}, {amount1:40,amount2:60,name:"ted"}]
let res = [items.reduce((ac,x) => {
for(let key in x){
if(typeof x[key] === "number"){
if(!ac[key]) ac[key] = 0;
ac[key] += x[key]
}
}
return ac;
},{})]
console.log(res)
reduce() is indeed the way to go, but the cleanest to go only through a set of known keys is probably to pass your expected result as the accumulator and to iterate over this accumulator's keys:
const items = [
{ amount1: "100", amount2: "50", name: "ruud", foo: "unrelated" },
{ amount1: "40", amount2: "60", name: "ted", foo: "0" }
];
const result = items.reduce((acc, item) => {
for (let key in acc) { // iterate over the accumulator's keys
acc[key] += isNaN(item[key]) ? 0 : +item[key];
}
return acc;
}, { // here we define the expected format
amount1: 0,
amount2: 0
});
console.log(result);

convert JSON object to a different one

i have this json:
[
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
]
and i want to convert it to:
[
{ "name": "AF28110", "price": 33456.75},
{ "name": "AF27989", "price": 13297.26}
]
I have tried various making it with .map() but i cannot make it work.
does anyone have any idea how to do this?
thank you
You can try following code:
let output = [];
input.forEach(obj => Object.getOwnPropertyNames(obj).forEach(key => output.push({name: key, price: obj[key]})))
Object.getOwnPropertyNames will give you names of your properties and then you can transform each name to a separate output array item.
Using map:
const data = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
]
const out = Object.keys(data[0]).map(el => {
return { name: el, price: data[0][el] };
});
console.log(out)
Here's a way using concat, Object.keys, and map. You can take each item from the array, get the keys from that object, and then map each key to the name/price object you want. Do that for each item, then flatten the result (using concat).
Example:
const arr = [{
"AF28110": 33456.75,
"AF27989": 13297.26
}]
const result = [].concat(...arr.map(o => Object.keys(o).map(k => ({name: k, price: o[k]}))))
console.log(result);
If you have multiple objects on the array, you can use reduce
let arr = [
{"AF28110": 33456.75,"AF27989": 13297.26},
{"AF28111": 33456.20,"AF27984": 13297.88}
];
let result = arr.reduce((c, v) => c.concat(Object.entries(v).map(o => {return {name: o[0],price: o[1]}})), []);
console.log(result);
Try this,
var text = '[{"AF28110": 33456.75,"AF27989": 13297.26}]';
var obj = JSON.parse(text);
var result = [];
for (i = 0; i < obj.length; i++) {
var keys = Object.keys(obj[i]);
for (j = 0; j < keys.length; j++){
result[j] = '{ "name":' +keys[j] + ', "price":' + obj[i][keys[j]]+'}';
}
}
console.log(result);
Thanks.
Ways to achieve :
Using Object.keys method :
var jsonObj = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
];
var res = Object.keys(jsonObj[0]).map(item => {
return {"name": item, "price": jsonObj[0][item] };
});
console.log(res);
Using Object.getOwnPropertyNames method :
var jsonObj = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
];
var res = Object.getOwnPropertyNames(jsonObj[0]).map(item => {
return {"name": item, "price": jsonObj[0][item] };
});
console.log(res);

Categories

Resources