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}
}
}
Related
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
}
});
This question already has an answer here:
How do I access an object property dynamically using a variable in JavaScript?
(1 answer)
Closed 2 years ago.
I have this array of objects and I want to show all value in each object:
var array = [{obj1:{property1:"value1",property2:"value2",property3:"value3"}},
{obj2:{property1:"value1",property2:"value2",property3:"value3"}},
{obj3:{property1:"value1",property2:"value2",property3:"value3"}}];
When I try something like this I only get to show the key but not the value
for (let i in array){
for (let key1 in array[i]) {
Any help?
The Object.values() returns an array of values of the Object passed to it.
You can then use flatMap twice to flatten the nested object array and fetch all the values.
var array = [{
obj1: {
property1: "value1",
property2: "value2",
property3: "value3"
}
},
{
obj2: {
property1: "value1",
property2: "value2",
property3: "value3"
}
},
{
obj3: {
property1: "value1",
property2: "value2",
property3: "value3"
}
}
];
function getAllValues(array) {
return array.flatMap(o => Object.values(o))
.flatMap(o => Object.values(o))
}
console.log(getAllValues(array));
This question already has answers here:
Find and remove objects in an array based on a key value in JavaScript
(14 answers)
Closed 5 years ago.
I would like to delete an object from a JSON objects array.
Here is the array:
var standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
For example how can I delete the object whose key is "Q": "Drinks" ?
Preferably of course without iterating the array.
Thanks in advance.
You have to find the index of the item to remove, so you'll always have to iterate the array, at least partially. In ES6, I would do it like this:
const standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
const index = standardRatingArray.findIndex(x => x.Q === "Drinks");
if (index !== undefined) standardRatingArray.splice(index, 1);
console.log("After removal:", standardRatingArray);
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