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 1 year ago.
Improve this question
having this type of data
{
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
and expected result
[
{
"key1": "time_1",
"key2": 20,
},
{
"key1": "time_2",
"key2": 10,
},
{
"key1": "time_3",
"key2": 40,
},
{
"key1": "time_4",
"key2": 30,
}
]
How to convert object to array using JavaScript? I have updated my question.
You could use the Object.keys() methods to iterate over your object and then use the Array.map() method to transform your object to the array structure you need.
var data = {
"0": "value1",
"1": "value2"
}
var newData = Object.keys(data).map(key => ({
[key]: data[key]
}))
console.log(newData)
--Update--
You would simply need to change the object being returned from the callback function passed to the .map() method.
var data = {
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
var newData = Object.keys(data).map(key => ({
"key1": key,
"key2": data[key]
}))
console.log(newData)
given data
const data = {
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
get all keys of data object
const KeysOfData = Object.keys(data);
get expected output like this - [
{
"key1": "time_1",
"key2": 20,
},
]
const result = KeysOfData.map(key => {
const value = data[key]
return {
key1: key,
key2: value
}
});
Related
This question already has answers here:
JavaScript - cannot set property of undefined
(8 answers)
Closed 1 year ago.
I want to create JSON object using pure JavaScript as below:
{
"0": {
"0": {
"key1": 1,
"key2": 2
},
"1": {
"key1": 1,
"key2": 2
}
}
"1": {
"0": {
"key1": 1,
"key2": 2
}
}
}
But when I try below code I get error for undefined:
var myJosnObj = {};
myJosnObj["0"]["0"] = {"key1": 1,"key2": 2};
I am getting error:
Error: myJosnObj[0] is undefined
I want to either create or update the existing key in the json document.
const myJosnObj = {};
myJosnObj["0"] = {}
myJosnObj["0"]["0"] = {"key1": 1,"key2": 2};
You need to define myJosnObj["0"]
you can directly do :
const myJosnObj =
{ "0":
{ "0": { "key1": 1, "key2": 2}
, "1": { "key1": 1, "key2": 2}
}
, "1":
{ "0": { "key1": 1, "key2": 2}
}
}
This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 3 years ago.
I have a list for order of field to display
field_order = ["name", "age", "birthday"]
I got a list of objects like this
_data_set = {
"age": 23,
"birthday": "2000-12-12"
"name": "A"
}
I need to order Object keys according to field_order.
Expected result:
_data_set = {
"name": "A",
"age": 23,
"birthday": "2000-12-12"
}
Key order is chronological in JavaScript since ES2015, so we can order like so:
There's a nice article on this: property-traversal-order-es6
field_order = ["name", "age", "birthday"]
_data_set = {
"age": 23,
"birthday": "2000-12-12",
"name": "A"
};
let result = field_order.reduce( (obj, v) => {
obj[v] = _data_set[v];
return obj;
}, {});
console.log(result);
At first you need to sort and then just create an object with desired order of keys:
let field_order = ["name", "age", "birthday"];
let _data_set = {
"age": 23,
"birthday": "2000-12-12",
"name": "A"
}
let order = {name: -1, age: 0, birthday: 1};
const result = {};
Object.keys(_data_set)
.sort((a,b)=> order[a] - order[b])
.forEach(key=> result[key] = _data_set[key]);
console.log(result);
You could use the following:
let new_data_set = {};
for(let item of field_order) {
new_data_set[item] = _data_set[item];
}
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 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 5 years ago.
Improve this question
I can ordering a-z using the .sort() method in javascript, but I would get a JSON like this: (With a "A-Z" index containing the result)
data: {
"A": [
{
"name": "Anh Tuan Nguyen",
"age": 28
},
{
"name": "An Nguyen",
"age": 20
},
],
"Z": [
{
"name": "Zue Dang",
"age": 22
},
{
"name": "Zoom Jane",
"age": 30
},
]
}
var names = [{name:"a1"},{name:"a2"},{name:"b1"},{name:"b2"}.....];
var data = {};
for (var i = 0; i < names.length; i++) {
var n = names[i].name.subStr(0,1);
if (data[n] == null)
data[n] = [];
data[n].push(names[i]);
}
There is no way to sort a JSON data structure, however, we can do it by using the following process:
Get your data keys with Object.keys(myResults.data)
Sort you keys
Create a reduce function to transform your ordered keys into an ordered object
The snippet is here, I hope it helps:
var myResults = {
data: {
C: [
{
"name": "Kevin Doe",
"age": 22
}
],
A: [
{
"name": "Alex Doe",
"age": 31,
}
],
B: [
{
"name": "Boris Doe",
"age": 22
},
{
"name": "Birdo Doe",
"age": 30
},
]
}
};
var originalData = myResults.data;
// 1. get the keys
var dataKeys = Object.keys(originalData);
// 2. sort the keys
var sortedKeys = dataKeys.sort();
// 3. create the object again
var orderedData = sortedKeys.reduce(function(result, key) {
return Object.assign(
{},
result,
{ [key]: myResults.data[key] }
);
}, {});
document.getElementById('original').innerHTML = JSON.stringify(originalData);
document.getElementById('sorted').innerHTML = JSON.stringify(orderedData);
h3 {
margin: 0;
}
code {
display: block;
margin-bottom: 15px;
padding: 10px;
background-color: #f9f9f9;
}
<h3>Original Data</h3>
<code id="original"></code>
<h3>Ordered Data</h3>
<code id="sorted"></code>
JavaScript objects are not ordered. If you want to iterate over an object's properties, you can sort the keys and then retrieve your values:
const result = {
data: {
Z: [],
F: [],
A: [],
D: []
}
};
Object
.keys(result.data)
.sort()
.map(key => console.log(key, result.data[key]));
UPDATE:
Exist a JavaScript library that make It possible: Lodash Utilities (https://lodash.com/docs/4.17.4). Contain methods for .sort() JSON (no Arrays) and a method to obtain the JSON for I asked in this question. I only did this:
//First, order my JSON alphabetically with _.sortBy method (I can even order by a nested property in my JSON)
var order = _.sortBy(require('./names'), function (el) { return el.name });
//Second, I group my order result by the first letter of my property 'name' in my JSON
var list = _.groupBy(order, (b) => b.name[0].toUpperCase());
This is my input:
[
{"name":"Mark"},
{"name":"Jul"},
{"name":"Alicia"},
]
This is my output:
[
"A": [
{
"name": "Alicia"
}
],
"J": [
{
"name": "Jul"
},
],
"M": [
{
"name": "Mark"
},
]
I hope this help to somebody!
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
i want have a value for a specific key may be nested value also like change value of key1 to value100 or key11 to value111.
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"map1" : {"key4":"value4",
"key5":"value5",
"key6":"value6",
"map2" :
{
"key7":"value7",
"key8":"value8",
"key9":"value9",
"map3" :
{
"key10":"value10",
"key11":"value11",
"key12":"value12"
},
"map4" :
{
"key13":"value13",
"key14":"value14",
"key15":"value15"
}
}
}
}
how to achieve this using javascript or jquery. please help me to find out the issue.
If you stored that in a variable like
var object = { *your JSON here*}
you can access it like:
object.key1
to obtain the value of your key1
If you want to get those in map2, it would be:
object.map2.key7
e.g.
If you want to change values, just do
object.key = *value*;
You can just hold your json on javascript object and edit it.
var _j ={
"key1": "value1",
"key2": "value2",
"key3": "value3",
"map1" : {"key4":"value4",
"key5":"value5",
"key6":"value6",
"map2" :
{
"key7":"value7",
"key8":"value8",
"key9":"value9",
"map3" :
{
"key10":"value10",
"key11":"value11",
"key12":"value12"
},
"map4" :
{
"key13":"value13",
"key14":"value14",
"key15":"value15"
}
}
}
};
_j.key1 = "New Key1";
$('div').html(JSON.stringify(_j));
Here is working JS Fiddle