Convert Object to JSON Object - javascript

I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.

This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});

You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.

Related

What does this Javascript object syntax means? It has a key (a string) and a value (object)

I am following a tutorial on Youtube about importing data into existing todo list component in React.
If you look at the code below, at the const data object, there are two keys namely lists and listIds. There are two parts which I don't understand.
Why is the key "list-1" a string while the value {id: "list-1",title: "Todo",cards,}
is a normal object? I could not figure out this syntax. If it's JSON format, both key-value should be a in quotation marks.
Is the listIds: ["list-1"] just a normal key-value pair which has an array as its value? If so, why does it has the same name as the one from the initial lists keys? Is this a Destructuring method from ES6?. I just cannot understand the syntax.
const cards = [
{
id: "card-1",
title: "Learning how to cook",
},
{
id: "card-2",
title: "Making sandwich",
},
{
id: "card-3",
title: "Taking the trash out",
},
];
const data = {
lists: {
"list-1": {
id: "list-1",
title: "Todo",
cards,
},
},
listIds: ["list-1"],
};
export default data;
Because "list-1" contains a minus sign and that would be an error for an identifier name. It would be like trying to subtract 1 from "list" and use the expression as a key.
listIds : ["list-1"] is a normal JS key-value expression with a key to the left of : and an array with a single string value to the right.
Object data.lists looks like it contains various sub-objects, each having an ID and listIds is just an array containing all the keys in lists. In your example there is one sub-object and correspondingly, one key in listIds.
One more thing: In a JSON string, keys to the left of : must be in double quotes, however this is a Javascript object, and Javascript objects can have keys without double quotes as long as each key is formatted as a regular Javascript variable, as well as values to the right of : that many times cannot be represented in a JSON string, such as functions for example.
I just thought I'd add a little summary here about declaring key/value pairs in an object declaration. When you declare an object property as in:
let obj = {prop: value};
the left hand side of the property declaration is the property name. There are three possible syntaxes allowed for that:
Plain String - No Quotes
// no quotes - this is allowed when the property name
// doesn't contain any reserved characters
let obj = {prop: value};
Quoted String
// quotes - this is always allowed, but is required when the property name
// does contain reserved characters like a "-" such as your example of "list-1"
let obj = {"prop": value};
Brackets around a variable name
// computed property name. This is used when the property name you want to use
// is in a variable
let someVar = "prop";
let obj = {[someVar]: value};
All three of these options above create the exact same key/value pair in that object.
The right hand side of the prop: value pair can be any Javascript expression like these:
let obj = {prop: 3}; // a number
let obj = {prop: "foo"}; // a string
let obj = {prop: value}; // value from some variable
let obj = {prop: [1,2,3]}; // an array
let obj = {prop: resultFromCallingFunc()}; // the result from calling some function
let obj = {prop: {greeting: "hello"}}; // another object
let obj = {prop: 3 + 4}; // any expression

Javascript array vs object

This might be a noob question for you guys but I just want to clarify something. I'm new to JS and I know that arrays are just objects with fields as indexes.
I have some lines of code here. The objective is pretty easy, is to pass a parameter function to an array and map it to another one.
My confusion is that the _obj is declared as an object with _obj = {}, and we have to do _obj[obj.key] = obj.value to map the keys and values. What is actually going around here?
It makes me feel like there are two nested arrays and it feels gross. I hope you understand me and I just need to know if there is another way or what actually is going on.
Stay at home guys!
Thanks in advance.
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.map(obj => {
let _obj = {};
_obj[obj.key] = obj.value;
return _obj;
});
console.log(newArray);
//Array [Object { 1: 10 }, Object { 2: 20 }, Object { 3: 30 }, Object { 4: 40 }]
I just need to know if there is another way or what actually is going
on.
When you do:
_obj[obj.key] = obj.value;
... you are setting a key/property on the object _obj to hold a particular value. In this case, the key you are setting is the value of obj.key and the value is obj.value. The values of obj.key and obj.value changes depending on what object you are iterated on in the .map() callback. For example, if you are looking at the first object in your array, obj.key would be 1 and obj.value would be 10. Thus, doing _obj[obj.key] = obj.value would be equivalent to _obj[1] = 10, which sets the key of 1 to have the value of 10 on the _obj object:
{
1: 10
}
This process occurs for each object in your array.
As for a different approach, you could use computed-property names introduced in ES6 with destructuring assignment to return an object literal with the key property as the key for the new object literal and the value property and the actual value for the new object:
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.map(({key, value}) => ({[key]: value}));
console.log(newArray);
In javascript, just like java, everything that is not a primitive is an object. Arrays are actually an object that just have some utility functions added in, such as the length attribute, and .map. To access a property, you can either do obj.prop, or use an arbitrary string like python's dictionaries like obj["prop"].
Array is special object, In which all key should be Number. The array has some pre-defined method, Which is made to iterate and perform similar operations. The array is linear and implements stack implementation. Array element could be any other object or Array.
To understand:
const object = {
1: "something",
2: "something2"
}
const object2 = {
"1_1": "something",
"2_1": "something2"
}
// console.log(object[1])
// console.log(object[2])
// console.log(object2["2_1"]) // Key string
// console.log(object2["1_1"])
// object.forEach(console.log) // Error
const array = ["something", "something2"]
const array2 = []
array2["1_1"] = "something"
array2["2_1"] = "something2"
console.log(array[0]) // index start with 0, default
console.log(array[1])
console.log(array2["2_1"]) // Key string
console.log(array2["1_1"]) // Works
array.forEach(console.log) // No error, something 0 [ 'something', 'something2' ] something2 1 [ 'something', 'something2' ]
array2.forEach(console.log) // No error, // No output
Here is the variant with reduce method:
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.reduce((acc, rec) => { return {...acc, [rec.key]: rec.value} }, []);
console.log(JSON.stringify(newArray))
// {"1":10,"2":20,"3":30,"4":40}

Javascript associate array gives many undefined fields

I have an associate array with the key is the Id of the item. For example, the item id is 104, therefore the id of the object will be array[104] = {item.info};
So I have this in my component, but every time I am outputting my array it shows 1-103 values and all of them are null. How would I get rid of it and make the array output only what is stored.
JavaScript does not have associative array like in PHP.
What JavaScript has that is most similar to associative array is an object. The difference is that an object is not iterable, while an associative array is iterable.
What you currently do is basically:
const data = []; // [] is an array
data[10] = {
item: 1
};
console.log(data);
What you need to do should be something like this:
const data = {}; // {} is an object
data[10] = {
item: 1
};
console.log(data);
When you do json_encode() in PHP, it is actually converting associative array into a JSON, which is a valid JavaScript object, which do not support associative array as well.
So what it does would be something like this:
$data = [
'10' => [
'item' => 1
]
];
echo json_encode($data);
// output => { "10": { "item": 1 } }
Notice the {} syntax instead of [] syntax.
array doesn't have key, value. it just have value
if you use key, value data form, you should use object
let item = {104: item.info}
how to use object :
item[104]

Updating object properties and adding them in a new Arr with Reduce Javascript

I am trying to use reduce within addKeyAndValue function on an array of objects with properties of key-value pairs, add within each object a new key-value pair and return that on a new array. The addKeyAndValue func receives three arguments the arr, the key and the value to be added together within each object in the array. I then use push within Reduce callback to push the objects in the array to the new array in the accumulator with the updated new key and value using the bracket notation.
var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}]
function addKeyAndValue(arr, key, value){
return arr.reduce(function(acc, nextValue, idx){
console.log(next);
acc.push(nextValue[key] = value);
return acc;
},[]);
}
and the expected result should be:
addKeyAndValue(arr, 'title', 'Instructor') //
[
{title: 'Instructor', name: 'Alonso'},
{title: 'Instructor', name: 'James'},
{title: 'Instructor', name: 'Chris'},
{title: 'Instructor', name: 'Steve'}
]
however, the results that I get in my Chrome dev console is:
(4) ["Instructor", "Instructor", "Instructor", "Instructor"]
0:"Instructor"
1:"Instructor"
2:"Instructor"
3:"Instructor"
length:4
__proto__:Array(0)
I am wondering why is the Value passed through nextValue[key] overriding the whole object and returning just as a string. When I try to just push the existing objects in the new array it works fine but when pushing the nextValue[key] it turns undefined and when doing the above nextValue[key] = value it overrides the objects resulting into a new array with just instructor strings. I am a bit confused since I was expecting a different result.
Using the bracket notations nextValue[key] on nextValue which is each object within the array being iterated by the callback in the reduce method I thought that would add a new key property in this case "title" with the assigned value of "instructor".
Any help would be appreciated, Thanks :).
Your push argument only results in the value being pushed, not the object. You can solve this with the comma operator if your really want this in one expression:
acc.push((nextValue[key] = value, nextValue));
But it may be more readable if you do it separately:
nextValue[key] = value;
acc.push(nextValue);
You are pushing the result of the assignment into the array, instead of the object.
Since the result nextValue[key] = value is value. Using acc.push(nextValue[key] = value); is like doing acc.push(value).
Since you want to update each object, use Array#map to iterate the array. Clone each object (to prevent mutating the original objects) using Object#assign, and add the property:
var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
function addKeyAndValue(arr, key, value){
return arr.map(function(obj){
var clone = Object.assign({}, obj);
clone[key] = value;
return clone;
});
}
var result = addKeyAndValue(arr, 'title', 'Instructor');
console.log(result);
The ES6 version
const arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
function addKeyAndValue(arr, key, value){
return arr.map((obj) => Object.assign({ [key]: value }, obj));
}
const result = addKeyAndValue(arr, 'title', 'Instructor');
console.log(result);

How to create dynamically a simple json array?

I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]

Categories