Constructing a JSON from its path - javascript

I have a JSON document:
{
Customer: {
Name: "ddd",
Address: [
{Line1: "ABC", zip: [{d:"aa"},{d:"hh"} ,{d:"kk"}]},
{Line1: "XYZ", zip: [{d:"gg"},{d:"ff"}]}
]
}
}
I want the values of
[
"Customer.Address.0.Line1",
"Customer.Address.0.zip.0.d",
"Customer.Address.0.zip.1.d",
"Customer.Address.1.Line1",
"Customer.Address.1.zip.0.d",
"Customer.Address.1.zip.1.d"
]
modified into a new format as below
{
Entity: [
{d:"aa", Line1:ABC},
{d:"hh", Line1:ABC},
{d:"kk", Line1:ABC},
{d:"gg", Line1:XYZ},
{d:"ff", Line1:XYZ}
]
}
I actually need the data as below
{
"Entity.0.d":"aa",
"Entity.0.Line1":"ABC",
"Entity.1.d":"hh",
"Entity.1.Line1":"ABC",
"Entity.2.d":"kk",
"Entity.2.Line1":"ABC",
"Entity.3.d":"gg",
"Entity.3.Line1":"XYZ",
"Entity.4.d":"ff",
"Entity.4.Line1":"XYZ"
}
I need to find the path so that I can reconstruct the JSON.
How do I do that?

You can use dotty
var dotty = require("dotty");
var object = {
a: {
b: {
x: "y",
},
c: {
x: "z",
},
},
};
console.log(dotty.exists(object, "a.b.x")); // true
console.log(dotty.exists(object, ["a", "b", "x"])); // true
console.log(dotty.exists(object, "a.b.z")); // false
console.log(dotty.exists(object, ["a", "b", "z"])); // false
console.log(dotty.get(object, "a.b.x")); // "y"
console.log(dotty.get(object, ["a", "b", "x"])); // "y"
console.log(dotty.get(object, "a.b.z")); // undefined
console.log(dotty.get(object, ["a", "b", "z"])); // undefine

You can do something like:
var newJSON = new Object();
var keyArray = [];
for (var i=0; i< Customer.Address.length; i++){
for (var j=0; j< Customer.Address[i].zip.length; j++){
var innerJSON = new Object();
innerJSON.d = Customer.Address[i].zip[j].d;
innerJSON.Line1 = Customer.Address[i].Line1;
keyArray.push(innerJSON);
}
}
newJSON.key = keyArray;
console.log(JSON.stringify(newJSON)); //This line creates your new JSON string
Of course I am assuming that you have used JSON.parse on your first JSON string :)

Related

Adding object value array to separate array object

I have an array of objects, and and object with arrays as value. I'm trying to take the array from the object and add it as a value to a new key in the objects in the array. When you run the example below you see the object key is instead added as an array of its characters and I'm guessing I'm using Object.values() incorrectly?
So instead of the output being like;
{
"arrkey1": "arrvalue1",
"arrkey2": "arrvalue2",
"newStuff": [
"o",
"b",
"j",
"k",
"e",
"y",
"1"
]
}
How do I instead get what I want like;
{
"arrkey1": "arrvalue1",
"arrkey2": "arrvalue2",
"newStuff": [
"objValue1",
"objValue2",
"objValue3"
]
}
let arr1 = [
{
'arrkey1': 'arrvalue1',
'arrkey2': 'arrvalue2'
},
{
'arrkey3': 'arrvalue3',
'arrkey4': 'arrvalue4'
},
{
'arrkey5': 'arrvalue5',
'arrkey6': 'arrvalue6'
}
];
const obj1 = {
'objkey1': [
'objValue1',
'objValue2',
'objValue3'
],
'objkey2': [
'objValue4',
'objValue5',
'objValue6'
]
};
for (const item in obj1) {
for (let i = 0, x = arr1.length; i < x; i++) {
arr1[i].newStuff = Object.values(item);
}
}
console.log(arr1);
This example inserts a copy of obj1.objkey1 into each element of arr1:
let arr1 = [
{
'arrkey1': 'arrvalue1',
'arrkey2': 'arrvalue2'
},
{
'arrkey3': 'arrvalue3',
'arrkey4': 'arrvalue4'
},
{
'arrkey5': 'arrvalue5',
'arrkey6': 'arrvalue6'
}
];
const obj1 = {
'objkey1': [
'objValue1',
'objValue2',
'objValue3'
],
'objkey2': [
'objValue4',
'objValue5',
'objValue6'
]
};
const combined = arr1.map(item => ({newStuff: [...obj1.objkey1], ...item}));
console.log(combined);

When looping over an array of objects and adding data to a variable, it always adds an null along with the data

I have a an array of objects, and when I am looping over it add adding a value to a variable, the variable always has an nullin it. I know its a pretty basic question, but stuck on why it adds the null and don't know how to stop it.
(function() {
let ds = [{
Name: "A",
Age: 1
},
{
Name: "B",
Age: 2
},
{
Name: "C",
Age: 3
}
];
let str = null;
for (let i = 0; i < ds.length; i++) {
if (ds[i].Name) {
str += ds[i].Name + ",";
}
}
console.log(str);
})();
It shows as null, A, B, C, and what I want it to show as A,B,C
The value null is stringified to "null" - ToString . if you initialize it with empty string, will work.
(function() {
let ds = [{
Name: "A",
Age: 1
},
{
Name: "B",
Age: 2
},
{
Name: "C",
Age: 3
}
];
let str = "";
for (let i = 0; i < ds.length; i++) {
if (ds[i].Name) {
str += ds[i].Name + ",";
}
}
console.log(str);
})();

Assign attributes to values in array js/jquery

In my script, a function uses the values in my teststim array.
var teststim = ["A", "B", "C"]
And I want to give 'attributes' to these values, so that for example A has the attribute "name", B "birthday", ...
I need to find a way to have access to these attributes. I thought about something like this:
var teststim = {content: "A", attribute: "name"},
{content: "B", attribute: "birthday"},
{content: "C", attribute: "whatever"}
Maybe I'm close than I think, but I am not able to access the 'attribute' values corresponding to the content values. What am I missing?
You need an array of objects:
var teststim = [{content: "A", attribute: "name"},
{content: "B", attribute: "birthday"},
{content: "C", attribute: "whatever"}];
for (var i=0; i<teststim.length; i++) {
var obj = teststim[i];
if (obj.content=='C') {
alert(obj.attribute); // "whatever"
};
};
You can not give properties/attributes to the values of YOUR array.
Therefore, you must start with:
var arr = [
{content:'A'},
{content:'B'},
{content:'C'}
];
Now you can add new attributes, e.g.:
arr[0].attribute = '2';
If you want to map a value in the array to another (longer?) value, you can use:
var mapping = {"A" : "name",
"B" : "birthday",
"C" : "whatever"}
for(var i = 0, len = teststim.length; i < len; i++)
{
alert(mapping[teststim[i]]);
}
If not, then just have an array of objects:
var teststim = [{ 'content' : "A", 'attribute' : "name" },
{ 'content' : "B", 'attribute' : "birthday" },
{ 'content' : "C", 'attribute' : "whatever" }];
for(var i = 0, len = teststim.length; i < len; i++)
{
alert(teststim[i].attribute);
}

How to append this JavaScript array object to another JavaScript array object?

I have this Javascript json array object;
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
I want to append this array object dataJson to another object such that it looks like this;
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
], "rows": [
{c:
[{v:1},{v:90}] //dataJson[0]
},
{c:
[{"v":2},{"v":"33.7000"}] ////dataJson[1]
}
]};
How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.
Try this:
...
], "rows": dataJson.map(function(row) {return {c:row};})
};
Javascript objects are pretty amazing things. Just define a new field in chartObject as an array, and then push whatever json data you want into it. It looks you want rows to be an array of objects which have an identifier for each json object, but unless you explicitly want to name each dataJson with a string, then just use an indexed array:
chartObject["rows"] = [];
for(var i = 0; i < dataJson.length; i++) {
chartObject["rows"].push(dataJson[0]);
}
Now you can access each piece of data with:
chartObject["rows"][index]
And each field in the data with:
chartObject["rows"][index]["v"]
Using the simple and clean way:
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
]};
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
chartObject["rows"] = []; // start with empty array
// iterate over first dataJson array
for(var i = 0, len = dataJson[0].length; i < len; i++){
// push in array `c` mapped to the i-th element of dataJson[0]
chartObject["rows"].push({c : dataJson[0][i]["v"]});
}
console.log(chartObject);
DEMO
Ignore those [object Object] in DEMO
Sample Output:
{
cols: [{
id: "t",
label: "t_label",
type: "number"
}, {
id: "s",
label: "s_label",
type: "number"
}],
rows: [{
c: 1
}, {
c: 90
}]
}

Javascript array format for charts

I have two arrays
A =[1990,1991,....]
B=[a,b,c,d,e,f,...]
I want the resultant array in this format
Resultant=[{
name: 1990,
data: [a,b,c]
},{
name: 1991,
data: [d,e,f]
},...
]
Please help me how will I make it using for loops?
How about this:
var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });
This will format data with Array.prototype.map, based on your (rather vague) requirement:
var A = [1990,1991];
var B = ["a","b","c","d","e","f"];
var formatted = A.map(function (name, i) {
return {
name: name,
data: B.slice(i*3, i*3+3)
}
});
/*[
{
"name": 1990,
"data": [
"a",
"b",
"c"
]
},
{
"name": 1991,
"data": [
"d",
"e",
"f"
]
}
]*/
Assuming that for each in A, you want data to store 3 elements of B. I've stuck with your requirement of using for loops.
var Resultant = [];
for (var i = 0; i < a.length; i++) {
var data = [];
for (var j = 0; j < 3, B.length > 0; j++) {
data.push(B.shift());
}
Resultant.push({name: A[i], 'data': data});
}
This worked for me:
http://jsfiddle.net/s5zdD/ <-- see jsfiddle to show
A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];
var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
return {
'name':A[v],
'data': B.splice(0,3)
}
})
console.log(Resultant);

Categories

Resources