reading json from file in javascript - javascript

I have this json file:
test.json:
{"rows" : [
{"key": "value"},
{"key": "value"}
]
}
I tried this code to read it:
var json = require('test.json');
for (var row in json.rows) {
console.log(row.key);
}
it prints:
/usr/local/bin/node json-parser.js
undefined
undefined
What am I doing wrong?

Where row is the variable holding property name not the object, so you need to retrieve it using the property name ( Refer : for...in loop documentation). In your case it will be the index of array. There is no need to use for...in iterator here, a simple for loop is enough.
for (var row in json.rows) {
console.log(json.rows[row].key);
}
var json = {
"rows": [{
"key": "value"
}, {
"key": "value"
}]
};
for (var row in json.rows) {
console.log(json.rows[row].key);
}
With a simple for loop
for (var i=0;i < json.rows.length; i++) {
console.log(json.rows[i].key);
}
var json = {
"rows": [{
"key": "value"
}, {
"key": "value"
}]
};
for (var i = 0; i < json.rows.length; i++) {
console.log(json.rows[i].key);
}
Since the property holds an array useArray#forEach method to iterate.
json.rows.forEach(function(v){
console.log(v.key);
}
var json = {
"rows": [{
"key": "value"
}, {
"key": "value"
}]
};
json.rows.forEach(function(v) {
console.log(v.key);
})

Related

How to remove empty object in array?

I am trying to remove the empty object {} from the below structure.
data = [{
"total" : "value",
"status" : "statusVal",
"recs" : [{
"total" : "value",
"region" : "name",
"recs" : [{},{
"recs" : [{
"recs" : [{
"value" : "a",
"label" : "fn"
}]
}]
}]
}]
}]
This is my JavaScript code where I process the data and trying to remove the empty object from the result.
var result = json.parse(data);
for(var i=0;i<result.length;i++){
if(result[i].hasOwnProperty("recs")){
var fset = result[i].recs;
for(var j=0;j<fset.length;j++){
if(fset[j].recs === undefined || fset[j].recs === null){
delete fset[j].recs;
}
if(fset[j].hasOwnProperty("recs")){
var sset = fset[i].recs;
for(var k=0;k<sset.length;k++){
var tset = sset[i].recs;
if(sset[k].hasOwnProperty("recs")){
for(var z=0;z<tset.length;z++){
if(tset[z].hasOwnProperty("recs")){
// logic to push
}
}
}
}
}
}
}
}
I tried checking null and undefined and also with property check bool as false. Since the empty {} is always returning length as 1, that is also ruled out. I am stuck here on processing the removal of empty object.
Above code is removing the entire recs node. Can you help me find what I am missing?
Check the length of the Object.keys() to see if object is empty or not.
Object.keys(fset[j].recs).length === 0
You can't iterate all the dynamic levels of array manually, so better to write the function which has recursive function call.
var data = [{
"total": "value",
"status": "statusVal",
"recs": [{
"total": "value",
"region": "name",
"recs": [{}, {
"recs": [{
"recs": [{
"value": "a",
"label": "fn"
}]
}]
}]
}]
}]
function removeEmpty(ary) {
ary.forEach((item, index) => {
if (Object.keys(item).length === 0) { ary.splice(index, 1); }
else if (item.recs && item.recs.length > 0)
removeEmpty(item.recs)
});
}
removeEmpty(data)
console.log(data)

Return object with specific key:value pair in an array nested in another array - Javascript

I'm trying return an object from the code below that has the key value pair of name:sparky and return the entire metadata and stats array for that object.
I don't want to use Object.values(objectArray)[0] because this data is coming from an API and I expect the objects position in the array to change in the future.
I've tried objectArray.find but I don't know how to use that to find a value of an array which is inside another array. The value for name will always be unique and the actual objectArray has many more objects inside of it.
Help would be greatly appreciated!
Code
objectArray = [
{
"metadata": [
{
"key": '1',
"name": "sparky"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
},
{
"metadata": [
{
"key": '1',
"name": "abby"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
}
]
Desired result
{
"metadata": [
{
"key": '1',
"name": "sparky"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
}
I guess you can do following:
function getObjectForName(key, name) {
var filteredMetadata = [];
for(var i=0; i< objectArray.length; i++) {
filteredMetadata = objectArray[i].metadata.filter((val) => val[key] === name)
if(filteredMetadata.length) {
return objectArray[i];
}
}
}
getObjectForName('name', 'sparky')
What this code basically does is, iterates through all objects and check if name is sparky, if yes just break it. If you want to return all occurrences matching name, you need to add all of them to another array and return it.
You can simply use Reduce
let objectArray = [{"metadata":[{"key":'1',"name":"sparky"}],"stats":[{"statsFieldOne":"wins"},{"statsFieldTwo":"kills"}]},{"metadata":[{"key":'1',"name":"abby"}],"stats":[{"statsFieldOne":"wins"},{"statsFieldTwo":"kills"}]}]
let op = objectArray.reduce(( op,{metadata,stats} ) =>{
let found = metadata.find(({name})=>name==='sparky')
if(found){
op.push({metadata:found,stats})
}
return op
},[])
console.log(op)

JSON Data Fuzzy merge

I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.

How to convert from a JSON array to a JSON object

I have this JSON that I'm getting back from a web service call:
{
"name": "My Name",
"path": "my path",
"id": "44",
"type": "my type",
"classes": "my classes"
},
{
"name": "his Name",
"path": "his path",
"id": "76",
"type": "his type",
"classes": "his classes"
}
I then need to convert it to this format
{
"44" : { "name" : "My Name", "path" : "my path" },
"76" : { "name" : "his Name", "path" : "his path" }
}
My initial naive attempt was this:
var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push({
rawData[i].id :
{
"path": rawData[i].path,
"name": rawData[i].name
}
});
which fails with syntax errors, so I eventually got to this:
var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push(rawData[i].id,
{
"path": rawData[i].path,
"name": rawData[i].name
});
and it mostly works. My array is populated, but the problem is that my myData array doesn't have the "44", and "76" part of the object, just the { "name" : "", "path" : "" } part. I expect this is due to a lack of understanding on my part of how JSON and javscript objects work.
Your desired output isn't an array, so that's your starting point. The output you've said you want is an object, not an array.
You build your result by creating a blank object and then adding the objects to it using id as the key:
var myData = {};
rawData.forEach(function(entry) {
myData[entry.id] = {
name: entry.name,
path: entry.path
};
});
Or if you don't want to use forEach (it's ES5, but can be shimmed for older browsers), the old-fashioned way:
var myData = {};
var index, entry;
for (index = 0; index < rawData.length; ++index) {
entry = rawData[index];
myData[entry.id] = {
name: entry.name,
path: entry.path
};
}
Don't use Array.prototype.push(), use the square bracket notation and define your output as an object not an array.
var myData = {};
for (var i = 0; i < rawData.length; i++) {
myData[rawData[i].id] = {
"path": rawData[i].path,
"name": rawData[i].name
}
}
You need to convert your id to a string?
var myData = {};
for (var i = 0; i < rawData.length; i++) {
myData[String(rawData[i].id)] = {
"path": rawData[i].path,
"name": rawData[i].name
};
}
A variation on what other posters have written:
// Create a new empty object.
var out = {};
// Loop over your array of objects
// Add the each object id as a key to the output object, and the object as the value.
for (var i = 0, l = arr.length; i <l; i++) {
var obj = arr[i];
out[obj.id] = obj;
// Delete the properties from the newly added object you don't want.
delete obj.id;
delete obj.type;
delete obj.classes;
}

How to access specific elements in a Json array?

I have a Json array which has the elements below:
"adjacencies", "data", "id", "name".
In some elements, "adjacencies" does not exist.
This is an example:
var JsonArray = [
{
"id" : "id1",
"name" : "name1",
"data" : {
"$type" : "circle",
"$color" : "#AEC43B"
}
}, //Without "adjacencies"
{
"id" : "id2",
"name" : "name2",
"data" : {
"$type" : "circle",
"$color" : "#AEC43B"
}
}, //Without "adjacencies"
{
"adjacencies": [
{
"nodeTo": "id1",
"nodeFrom": "id3",
"data": {
"$color": "#416D9C"
}
}
],
"id" : "id3",
"name" : "name3",
"data" : {
"$type" : "circle",
"$color" : "#AEC43B"
}
} //With "adjacencies"
];
The first and the second elements doesn't contain "adjacencies", but the third element does.
In the loop for (i = 0; i < JsonArray.length; i++) how do I access the third element?
Is there a .contain property for example?
Thanks in advance:)
One way to do it is by checking if the value is of type undefined:
for (i = 0; i < JsonArray.length; i++) {
var item = JsonArray[i];
if (typeof item.adjacencies !== "undefined") {
// item has adjacencies property
}
}
As an aside: this is not a JSON array -- it's a Javascript array. There are no JSON objects, no JSON arrays, no JSON nothing. The only JSON-y thing that exists is plain JSON, which is a serialization format.
use hasOwnProperty
So you can do this
for (i = 0; i < JsonArray.length; i++){
if( JsonArray[i].hasOwnProperty('adjacencies') ){
//Do something here
}
}

Categories

Resources