Reputation: 84
I'm turning JSON into an array and back into separate JSON objects (it has to do with React and children). The array below works fine, as does putting array elements into vars. But when I try to make an obj from them, the key does not work, it just stays as "myKey" - Why? What is the right way to turn array elements into objects?
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var fetch = require('isomorphic-fetch');
app.use(bodyParser.json());
app.use(methodOverride());
var promise = new Promise(function(resolve, reject) {
fetch('https://jsonplaceholder.typicode.com/posts/1').then(
function(response){
return response.json();
}
).then(function(jsonData){
result = []
for(var i in jsonData) {
result.push([i, jsonData [i]]);
}
var myKey = result[0][0];
var myValue = result[0][1];
var myJSON = {myKey : myValue}
console.log(myJSON);
});
});
Upvotes: 1
Views: 97
Reputation: 10148
There is a simple way you can get this working
var myJSON = {};
myJson.myKey = myValue;
myJson.myKey2 = myJsonValue2;
..
Upvotes: 0
Reputation: 4419
Because myKey
is interpreted as a value, not as a variable. You need to use the dynamic key syntax, which is:
{ [myKey] : myValue }
Complete code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var fetch = require('isomorphic-fetch');
app.use(bodyParser.json());
app.use(methodOverride());
var promise = new Promise(function(resolve, reject) {
fetch('https://jsonplaceholder.typicode.com/posts/1').then(
function(response){
return response.json();
}
).then(function(jsonData){
result = []
for(var i in jsonData) {
result.push([i, jsonData [i]]);
}
var myKey = result[0][0];
var myValue = result[0][1];
var myJSON = {[myKey] : myValue}
console.log(myJSON);
});
});
Upvotes: 2