I have JSON data
var json = {"options": {
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
And I want to add one more key with value to it using JavaScript, but I want it to be on the top like this:
var json = {"options": {
"new_key": "new_value",
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
How can I do it?
Objects do not guarantee property order in JavaScript, but arrays do. If the order really matters and you are allowed to change your JSON structure, I'd suggest to use an array instead to organize your data.
var json = {
"options": [
{"key": "key1", "value": "value1"},
{"key": "key2", "value": "value2"},
{"key": "key3", "value": "value3"}
]
};
Using this, you could push an element to the start of the array using the unshift method.
json.options.unshift({"key": "new_key", "value": "new_value"});
Although it is not required by any of the ECMAScript specs, nonetheless most implementations do retain the original order of keys in Objects, with the exception of keys with numeric values. You can see a lengthy discussion about the Chrome's implementation here: http://code.google.com/p/v8/issues/detail?id=164
If you want to utilize this, you will need to create a new Object:
var newOpts = {};
newOpts["new_key"] = "new_value";
for (var k in json.options) {
newOpts[k] = json.options[k];
}
json.options = newOpts;
However if you do actually turn your object into a JSON string, and send it to someone else, there is no guarantee that they will preserve the order when they parse the string back into an Object.
I was surprised to discover the widely used Express library for NodeJS actually relies on this behaviour for its format method.
JSON Objects have no order.
If order is important to you, consideer creating options as an array, then you can iterate and adding items in a specific order:
var json = {"options": [
{key: "new_key", value: "new_value"},
{key: "key1", value: "value2"},
{key: "key2", value: "value2"},
{key: "key3", value: "value3"},
]}
You can extend the object in the following way using vanilla JavaScript but again this won't set the order as others have noted.
extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
var json = {
"options": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
};
extend(json.options, {"new_key": "new_value"});
You could use the extend function the ordering of the objects would determine which parameters would be written first, but as stated by DanFromGermany there aren't many real-life cases where the order is relevant.
Related
I got a Javascript object which looks like this:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
}
}
I also got an array to which I push items like this:
myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
},
key3: { //the object that was added },
key4: { //the object that was added }
}
I tried doing it with the spread operator:
return {...object, ...myArr}
But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).
How do I concatenate the object and the array the way I want?
rather my myArray create myObject.
myObject = {}
myObject[item.itemId] = anotherDefinedObject;
Then
return {...object, ...myObject}
const obj = {key1: 1};
const myArr = [{key2: 2}];
myArr.forEach(val => Object.assign(obj, val));
console.log(obj); // {key1: 1, key2: 2}
What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code.
P.S. As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it.
I want to rebuild the existing key/value object into another array with only values of original object.
Here is a look.
var car = {"key1": value1, "key2": "value2", "key3": "value3"};
I want to change above javascript object into the following:
var new_car = [value1, value2, value3]
I need your help. Thanks for your time and consideration.
You could use Object.keys and map the values with Array#map.
Caveat: The order may be not guaranteed, because the properties of objects have no order.
var car = {"key1": 'value1', "key2": "value2", "key3": "value3"},
new_car = Object.keys(car).map(function (k) { return car[k]; });
console.log(new_car);
You can simply iterate it over using for :
var car = {"key1": "value1", "key2": "value2", "key3": "value3"};
var new_car = [];
for ( key in car)
{
new_car.push(car[key]);
}
Using lodash/underscore:
var car = {"key1": value1, "key2": "value2", "key3": "value3"};
var new_car = _.values(car);
So I've to different objects, getting data from different sources. I need to convert them into a single object so that I can ng-repeat them.
object1 = {
"key1":"value one",
"key2":"value two"
}
object2 = {
"key1":"value three",
"key2":"value four"
}
What I need is
object3 = [{
"key1":"value one",
"key2":"value two"},
{
"key1":"value one",
"key2":"value two"}
}];
I tried angular.merge but it only works if the keys are different. In my case, keys are gonna be the same, only data is gonna change.
Can anyone help append object1 to object2 to create something like object3 which is object1+object2.
I tried converting them to json string & concatenating them but it didn't work.
Array contact function is not working either.
This is just vanilla javascript. You want to make an array of from the objects.
var object1 = {
"key1": "value one",
"key2": "value two"
}
var object2 = {
"key1": "value three",
"key2": "value four"
}
var object3 = []; // empty array
// add the other objects to the array
object3.push(object1);
object3.push(object2);
if your objects are already arrays and you just want to concatenate them, you can use the concat function on arrays.
var object1 = [{
key: 'abc',
value: 1
}];
var object2 = [{
key: 'cbd',
value: 2
}];
// use the concat function to concatenate the arrays
var object3 = object1.concat(object2);
You can find more about arrays by reading the documentation found here.
If your objects are firebaseArray objects they have their own API. More can be found here.
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
I'm a little new to JSON and I'm having some trouble figuring out how to parse a JSON file that is structured like this:
{
"list1": [
[
"id1",
"id2",
"id3",
"id4"
],
[
"value1",
"value2",
"value3",
"value4"
]
],
"list2": [
[
"id1",
"id2",
"id3",
"id4"
],
[
"value1",
"value2",
"value3",
"value4"
]
]
}
I'm using the follow jQuery to get the JSON data:
var data = $.getJSON("jsonfile.json");
Example of what I want to do:
Get an item from "list2" for "value4", but I only know what "list2" > "value2" is. How can I parse the the JSON only knowing value2 and then get the value4 result?
I'm not even sure if I'm getting the JSON as a JS object correctly. Everytime I try to alert something from "data" I get undefined (except for when I do alert(data); it says [object Object].
First of all, $.getJSON is async which means you need to do:
$.getJSON("jsonfile.json").then(function (data) {
//use your data
});
The reason you get [object Object] when you alert data is because $.getJSON returns a promise object.
Get an item from "list2" for "value4", but I only know what "list2" >
"value2" is. How can I parse the the JSON only knowing value2 and then
get the value4 result?
For the above question I do not understand it... however you can access your lists and list items like:
data.list2[1][3]; //value4