Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need data structure like mokeData2 and sources data was like mokeData.
How can I convert mokeData to mokeData2 in javascript?
const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];
1) You can easily achieve the result using Object.fromEntries and map
const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];
const result = [Object.fromEntries(mokeData.map((s) => s.split(" ")))];
console.log(result);
2) You can also use reduce here as:
const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];
const result = [
mokeData.reduce((acc, curr) => {
const [key, value] = curr.split(" ");
acc[key] = value;
return acc;
}, {}),
];
console.log(result);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a json file:
[
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
}, {
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}]
Now I want to get a list of the keys of each "name" object. At the end there should be ths list
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
and save it into an array.
What i have tried
var mydata = JSON.parse("jsonstring").ingredients;
hope this is understanable?
for each data in the array (map)
you want the ingredient part (.ingredients),
extract the keys (Object.keys)
and flatten the array (.flat())
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
You may prefer loop style. the only difference is flattening occurs with ... operator.
var results = [];
for (let a of array) {
results.push(...Object.keys(a.ingredients))
}
My proposition is :
'use strict'
const array = [
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
},
{
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}
]
const mydata = array.map((val) => {
return Object.keys(val.ingredients);
}).flat();
console.log(mydata)
// expected output: Array ["rum", "coke", "gin", "tonic"]
// Now you can get :
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
Hope that help you? Thank
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an array like this
let data = ['String1', 'String2', 'String3', 'String4']
I need to convert this array to an array of objects like so:
data = [
{value: 0, label: 'String1'},
{value: 1, label: 'String2'},
{value: 2, label: 'String3'},
{value: 3, label: 'String4'}
]
How to achieve this most elegantly?
Use map():
const arr = ['String1', 'String2', 'String3', 'String4'];
const res = arr.map((label, value) => ({ value, label }));
console.log(res);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have array of objects like this
var a = [
{'time' : 1539664755070,'T-1': 23 },
{'time' : 1539665095442,'H-1': 24 },
{'time' : 1539666489560,'T-1': 42 },
{'time' : 1539665095442,'H-1': 27 },
{'time': 1539671682230,'H-1': 40.45,'T-2': 33},
{'time': 1539671682230,'T-2': 30.45,'T-1': 65},
{'time': 1539671682230,'T-2': 42.45,'H-1': 11},
{'time': 1539671682230,'T-1': 50.45,'T-2': 85}
];
I want to have data like this
data : {
'T-1' : [23,42,50.45],
'T-2' : [33,30.45,85],
'H-1' : [24,27,40.45,11]
}
How can i get this data from given data?
Here is a solution, if something is not clear, please lemme know:
const result = {};
a.forEach(object => {
// Loop on each entry in the original array
Object.entries(object).forEach(([key,value]) => {
// Loop through each entry of one entry of the original array
// (ex 'T-1', 'T-2')
if(key !== 'time') {
// It's a key that I'm interested in, so do logic
if(!result[key]) {
// If the key (example 'T-1') haven't been encountered yet,
// initialize it's entry in the result with an empty array
result[key] = [];
}
result[key].push(value);
}
});
});
Best use case for using Map instead of Key,Value arrays. Simplifies lot of things.
You can use array#reduce with Object.values() to create a hash of your key and add the values corresponding to it. Then using Object.assign() and spread syntax you can create the final object.
let data = [ {'time' : 1539664755070,'T-1': 23 }, {'time' : 1539665095442,'H-1': 24 }, {'time' : 1539666489560,'T-1': 42 }, {'time' : 1539665095442,'H-1': 27 }, {'time': 1539671682230,'H-1': 40.45,'T-2': 33}, {'time': 1539671682230,'T-2': 30.45,'T-1': 65},{'time': 1539671682230,'T-2': 42.45,'H-1': 11}, {'time': 1539671682230,'T-1': 50.45,'T-2': 85} ],
result = Object.assign({}, ...Object.values(data.reduce((r, o) => {
let keys = Object.keys(o).filter(k => k !== 'time');
keys.forEach(key => {
r[key] = r[key] || {[key] : []};
r[key][key].push(o[key]);
});
return r;
},{})));
console.log(result);
const data = a.reduce((acc, row) => {
// Loop over keys of each row.
Object.keys(row)
// Filter out the "time" keys.
.filter((key) => key !== 'time')
// Collect the values by key, storing them in the accumulator.
.forEach((key) => {
if (typeof acc[key] === 'undefined') {
acc[key] = []
}
acc[key].push(row[key])
})
return acc
}, {})
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 4 years ago.
Improve this question
Below JSON Object needs to be iterated and need result as below.
[
{"Aazam":1, "Jagannath":2, "Bharath Kumar M":4 },
{"Bharath Kumar M":1, "Syad":1 },
{"Bharath Kumar M":2 }
]
output needed (can be in map):
Aazam: 1
Jagannath: 2
Bharath Kumar M: 4, 1, 2
Syad: 1
I tried with ES 6 syntax, I am able to get key and values but I am not successful in forming the array as needed.
Solution should be generic.
You can have a object as a output with the unique keys and values for each key as an array that holds the values of all similar keys.
var arr = [{
"Aazam": 1,
"Jagannath": 2,
"Bharath Kumar M": 4
},
{
"Bharath Kumar M": 1,
"Syad": 1
},
{
"Bharath Kumar M": 2
}
];
var res = arr.reduce((acc, item) => {
var keys = Object.keys(item);
keys.forEach((key) => {
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item[key]);
});
return acc;
}, {});
console.log(res);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an array of object like
let myObj =[{
"60+": 0.1413972485314015,
"18-29": 0.0832178903621611,
"40-49": 0.1033361204013377,
"30-39": 0.0835906328864075,
"Under 18": 0.1326368677036551,
"50-59": 0.1224973366151133
}]
I want to sort the above array of object like
let myObj =[{
"Under 18": 0.1326368677036551,
"18-29": 0.0832178903621611,
"30-39": 0.0835906328864075,
"40-49": 0.1033361204013377,
"50-59": 0.1224973366151133
"60+": 0.1413972485314015,
}]
How can i achieve this kind of sorting using javascript ?
You could take an offset for Under and + quantifier and take the value, depending on the sorting position. Then return the delta of values or the delta of the offset.
Later, you could build a new object with sorted keys.
var object = { "60+": 0.1413972485314015, "18-29": 0.0832178903621611, "40-49": 0.1033361204013377, "30-39": 0.0835906328864075, "Under 18": 0.1326368677036551, "50-59": 0.1224973366151133 },
keys = Object
.keys(object)
.sort((a, b) => {
function getV(s, side) {
var offset = { 'Under': -1, null: 0, '+': 1 }[s.match(/Under|\+/)],
value = s.match(/\d+/g)[offset && side];
return { value, offset };
}
var aa = getV(a, 1),
bb = getV(b, 0);
return aa.value - bb.value || aa.offset - bb.offset;
}),
newObject = Object.assign(...keys.map(k => ({ [k]: object[k] })));
console.log(newObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use first character to sort and consider if first character is number it is small,
let myObj = [{
"60+": 0.1413972485314015,
"18-29": 0.0832178903621611,
"40-49": 0.1033361204013377,
"30-39": 0.0835906328864075,
"Under 18": 0.1326368677036551,
"50-59": 0.1224973366151133
}];
const ordered = {};
Object.keys(myObj[0]).sort(
function(a, b) {
if (isNaN(Number(a.charAt(0))))
return -1;
if (isNaN(Number(b.charAt(0))))
return 1;
return a.charAt(0) - b.charAt(0);
}
).forEach(function(key) {
ordered[key] = myObj[0][key];
});
console.log(ordered);
You can not do it directly. You have to change your structure. Something like this. I think the modified structure makes the same sense.
let myObj = [{
"60": 0.1413972485314015,
"29": 0.0832178903621611,
"49": 0.1033361204013377,
"39": 0.0835906328864075,
"18": 0.1326368677036551,
"59": 0.1224973366151133
}]
let result = Object.keys(myObj[0]).sort((a, b) => a - b).map(val => ({
[val]: myObj[0][val]
}));
console.log(result);