How can I change node name of my JSON? - javascript

How can I change the name of a node in my JSON?
My code:
childType = view
childName = view0
child=[];
child[childTipy]= {
childType:{
"tipo": childTipy,
"nome":childName,
}
};
childList.push(child[childTipy]);
minhasWindows = {"window": {
"nome": "Win2",
"title": "Win",
"childrens": childList
}
};
The resulting JSON:
{
"windows" : [
{
"window" : {
"nome" : "Win2",
"title" : "Win",
"childrens" : [
{
"childType" : {
"tipo" : "view",
"nome" : "view0"
}
}
]
}
}
]
}
I want the childType node to be the value of my var childType = "view". How can I change this?
PS: I have multiple childType values.

If you want the property to come from a variable, use array syntax to assign the property.
var childType = "view"; // String needs to be quoted
var childName = "view0"; // String needs to be quoted
var child = {}; // This must be an object, not array
child[childType] = {
tipo: childType, // Don't need to quote keys in object literals
nome: childName,
};
childList.push(child);
You also had too many levels in your child object.

Change this
childType:{
to
view:{

Replace
child=[];
child[childTipy]= {
childType:{
"tipo": childTipy,
"nome":childName,
}
};
with
child=[];
child[childTipy]= {};
child[childTipy][childType] = {
"tipo": childTipy,
"nome":childName,
};

If childType appears in the keys only:
var someJson = '{"windows":[{"window":{"nome":"Win2","title":"Win","childrens":[{"childType":{"tipo":"view","nome":"view0"}}]}}]}';
var newJson = $.parseJSON(someJson.replace('childType', 'view'));
Though I don't see any actual need of changing a key in place.

Related

Merge Multiple Objects (es5)

I have a requirement to merge two (or Multiple) Objects as a single object. While keeping each Object name as the parent key.
var event =
{ id : '45243'
, name : 'Cardiff locè'
, loc : 'Cardiff'
}
var alert =
{ node : 'sdwan edge'
, severity : 'critical'
}
The output should be like this:
var mergedObject =
{ event :
{ id : '45243'
, name : 'Cardiff loc'
, loc : 'Cardiff'
}
, alert:
{ node : 'sdwan edge'
, severity : 'critical'
}
}
mergeObject.event = event;
mergeObject.alert = alert;
That's not really merging. The existing objects are unchanged. You are just creating a new object.
var mergedObject = {
"event": event,
"alert": alert
};
var event = {
"id": "45243",
"name": "Cardiff loc",
"loc": "Cardiff"
}
var alert = {
"node": "sdwan edge",
"severity": "critical"
}
var mergedObject = {
event,
alert
};
console.log(mergedObject)

How to convert nested array of object into array of strings in Reactjs?

I want to map and convert the below JSON structure to array of simple string but getting the undefined error while mapping.
JSON structure :
var yourArray = [
{
"options": [
{
'id':1,
'name':'All'
},{
'id':2,
'name':'Javascript'
},{
'id':2000,
'name':'Ruby'
}
]
}
];
Trying to map like this :
var newArray = yourArray.map( function( el ){
yourArray.options.map( function( eln ){
return eln.name;
})
});
console.log (newArray);
Note: Following this example How do I convert a javascript object array to a string array of the object attribute I want?
Two issues you had in your code
There was no return var newArray = yourArray.map( function( el ){
el.options.map( function( eln ) here.
second yourArray.options you need to access using index or the el you're getting in your function call as argument.
var yourArray = [{"options": [{'id':1,'name':'All'},{'id':2,'name':'Javascript'},{'id':2000,'name':'Ruby'}]}];
var newArray = yourArray.map( function( el ){
return el.options.map( function( eln ){
return eln.name;
})
});
console.log (newArray);
UPDATE:
Thanks for the answer, sorry to bother you again, My actual JSON
structure is like this { "brand": [ {"options": [{"catgeory_name":
"Sigma"},{"catgeory_name": "Footner"}]} ] } How can we map this to get
the output like this ["Sigma", "Footner"] Because I am still getting
undefined error when I map
let data = { "brand": [ {"options": [{"catgeory_name": "Sigma"},{"catgeory_name": "Footner"}]} ] }
let op = data.brand[0].options.map(({catgeory_name})=>catgeory_name)
console.log(op)
here is the simple solution using map, since the option is inside the first index, you can user yourArray[0]
var yourArray = [
{
"options": [
{
'id':1,
'name':'All'
},{
'id':2,
'name':'Javascript'
},{
'id':2000,
'name':'Ruby'
}
]
}
];
var newArray = yourArray[0].options.map(i => i.name)
console.log(newArray)

How to access other object sibling's value?

I'm just wondering if it's possible to refer to self (object) value inside the object sibling like below?
[
{
"name": "Zulh",
"name_uppercase": uppercase(self.name) // expects ZULH
},
{
"name": "John",
"name_uppercase": uppercase(self.name) // expects JOHN
}
]
Note:
Code for uppercase is omitted for brevity. In my real code, it's doing synchronous complex stuff and is not actually simple string case manipulation like that.
Using a GETTER
If you want to keep it dynamic and make it work even if you change the name property, you can use a GETTER to do this kind of thing:
const names = [
{
"name": "John",
get name_uppercase() {
return this.name.toUpperCase();
}
}
]
console.log(names[0].name_uppercase)
GETTER for multiple objects
You don't have to write this for every property manually! Use .forEach:
const names = [
{
"name": "John"
},
{
"name": "Mike"
}
]
names.forEach(object => {
Object.defineProperty(object, 'nameUppercase', {
get: function() { return this.name.toUpperCase() }
});
});
console.log(names[0].nameUppercase)
console.log(names[1].nameUppercase)
Using a class and a GETTER
Or as #Rajesh pointed out you can use a class instead:
class Person {
constructor(name) {
this.name = name;
}
get nameUpperCase() {
return this.name.toUpperCase();
}
}
const names = [ new Person("John"), new Person("Mike")];
console.log(names[0].nameUpperCase);
console.log(names[1].nameUpperCase);
You can't reference an object during initialization when using object literal syntax.. Inshort, that's not possible what you expect above
Well, you can use map and add additional/modified properties to you object like
data.map(o=> ({name: o.name, upper_case : o.name.toUpperCase()}))
var data = [
{
"name": "Zulh"
},
{
"name": "John"
}
];
var x = data.map(o=> ({name: o.name, upper_case : o.name.toUpperCase()}))
console.log(x)
You can use Array.forEach and update the objects in Array
var data = [{"name": "Zulh"},{"name": "John"}];
data.forEach(o=> o.upper_case = o.name.toUpperCase());
console.log(data);
Why not create a function that transforms your incoming array? A way to do it could be like this:
const value = [
{
"name": "Zulh"
},
{
"name": "John"
}
];
const transform = ( array, propertyToUpdate, propertyToCreate, transformation ) => {
return array.map( item => ({ ...item, [propertyToCreate]: transformation( item[propertyToUpdate] ) }) );
};
console.log( transform( value, 'name', 'name_uppercase', ( item ) => item.toUpperCase() ) );
You can't do this with the object literal syntax, since it's 'this' property will not be set at that time. For example, if you'd run your code in the browser, 'this' would refer to the window object.
So you'll either have to use one of the other answers or go for a 'class':
var uppercase = function( str ) {
return str.toUpperCase();
};
var Person = function( name ) {
this.name = name;
this.name_uppercase = uppercase( this.name );
};
var persons = [
new Person( 'zuhi' ),
new Person( 'john' )
];
console.log( persons );
Same can be written in ES6 class syntax.
I would suggest 2 approaches:
If you DO NOT want to change your initial array ( which is recommended ), use map which returns a new array with changed values ( calls a function for every array item ) .
See below
let arr = [
{
"name": "Zulh",
},
{
"name": "John",
}
];
const newArr = arr.map((x)=>{
x.name_uppercase = (x.name).toUpperCase()
return x
})
console.log(newArr)
If you don't mind changing your initial array, you can use forEach. Keep in mind that unlike map, forEach changes your array and so it doesn't return anything.
let arr = [
{
"name": "Zulh",
},
{
"name": "John",
}
];
arr.forEach((x)=>{
x.name_uppercase = (x.name).toUpperCase()
})
console.log(arr)
So it all depends if you want to change your current array or not
How about using a getter method?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
The get syntax binds an object property to a function that will be
called when that property is looked up.
foo = [
{
"name": "Zulh",
get name_uppercase () {
return (this.name).toUpperCase();
}
},
{
"name": "John",
get name_uppercase () {
return (this.name).toUpperCase();
}
}
]
console.log(foo[1].name_uppercase); //returns JOHN
Hope it helps :)

Get the closest match in a string

I have a json file with some domains which I try to match in a foreach object function.
JSON-File:
"calendar-google": {
"domainMatch": "calendar.google",
"icon": "assets/icons/google-calendar.png"
},
"inbox-google": {
"domainMatch": "inbox.google",
"icon": "assets/icons/google-gmail.png"
},
"github": {
"domainMatch": "github",
"icon": "assets/icons/github.png"
},
"google": {
"domainMatch": "google",
"icon": "assets/icons/google-google.png"
},
"trello": {
"domainMatch": "trello",
"icon": "assets/icons/trello.png"
},
"tweetdeck": {
"domainMatch": "tweetdeck.twitter",
"icon": "assets/icons/twitter.png"
},
"twitter": {
"domainMatch": "twitter",
"icon": "assets/icons/twitter.png"
},
"youtube": {
"domainMatch": "youtube",
"icon": "assets/icons/youtube.png"
}
Now I want to check if my url in my local storage does match with one of these "domainMatch" properties.
JavaScript:
$.getJSON("domainList.json", function (data) {
Object.getOwnPropertyNames(data).forEach(function(val, idx, array) {
var domainMatch = data[val].domainMatch
if(localStorage.getItem("favouriteSite")) {
var sites = JSON.parse(localStorage.getItem("favouriteSite"));
// Lets think firstlink is "calender.google.com"
var firstLink = sites.site1.link;
if(firstLink.includes(domainMatch)){
// 2 Results but I want only that
// result which is near!!
}
}
});
You see in the comment, that I not want the match "google" and "calender.google". I want only the nearest match from both (calender.google in this case).
How can I get the nearest match of a string?
When I did not write something detailed enough, then please write it but I think you should understand what I mean.
Greetings
Julian
Use Array.prototype.some() function to return the result immediately on the first match:
$.getJSON("domainList.json", function (data) {
var matched = Object.keys(data).some(function(k) {
var domainMatch = data[k].domainMatch;
if (localStorage.getItem("favouriteSite")) {
var sites = JSON.parse(localStorage.getItem("favouriteSite"));
// Lets think firstlink is "calender.google.com"
var firstLink = sites.site1.link;
return firstLink.includes(domainMatch);
}
};
});
Instead of forEach, use find to get the first match or null if nothing is matched like this:
$.getJSON("domainList.json", function(data) {
var sites = JSON.parse(localStorage.getItem("favouriteSite")); // this should be out here (so you won't fetch it evertime)
var firstLink = sites.site1.link;
var val = Object.keys(data).find(function(key) { // find will stop at the first found item (Object.keys) is better since it's just a plain object)
var domainMatch = data[key].domainMatch;
return firstLink.includes(domainMatch);
});
console.log(val); // val will be the first matched key ('github', 'google', ...) or null if nothing is matched
/***************** EDIT: **********************/
if(val) { // if we found something
var obj = data[val]; // get the object (because val is the key)
var icon = obj.icon; // now obj is an object from the array data (you can access its icon property like this)
}
});

Search for a related json data

How can i find data that is related to the already known data?
( I'm a newb. )
For example here is my json :
[
{ "id": "1", "log": "1","pass": "1111" },
{ "id": 2, "log": "2","pass": "2222" },
{ "id": 3, "log": "3","pass": "3333" }
]
Now i know that "log" is 1 and i want to find out the data "pass" that is related to it.
i've tried to do it so :
The POST request comes with log and pass data , i search the .json file for the same log value and if there is the same data then i search for related pass
fs.readFile("file.json", "utf8", function (err, data) {
var jsonFileArr = [];
jsonFileArr = JSON.parse(data); // Parse .json objekts
var log = loginData.log; // The 'log' data that comes with POST request
/* Search through .json file for the same data*/
var gibtLog = jsonFileArr.some(function (obj) {
return obj.log == log;
});
if (gotLog) { // If there is the same 'log'
var pass = loginData.pass; // The 'pass' data that comes with POST request
var gotPass = jsonFileArr.some(function (obj) {
// How to change this part ?
return obj.pass == pass;
});
}
else
console.log("error");
});
The problem is that when i use
var gotPass = jsonFileArr.some(function (obj) {
return obj.pass == pass;
});
it searches through the whole .json file and not through only one objekt.
Your main problem is that .some() returns a boolean, whether any of the elements match your predicate or not, but not the element itself.
You want .find() (which will find and return the first element matching the predicate):
const myItem = myArray.find(item => item.log === "1"); // the first matching item
console.log(myItem.pass); // "1111"
Note that it is possible for .find() to not find anything, in which case it returns undefined.
The .some() method returns a boolean that just tells you whether there is at least one item in the array that matches the criteria, it doesn't return the matching item(s). Try .filter() instead:
var jsonFileArr = JSON.parse(data);
var log = loginData.log;
var matchingItems = jsonFileArr.filter(function (obj) {
return obj.log == log;
});
if (matchingItems.length > 0) { // Was at least 1 found?
var pass = matchingItems[0].pass; // The 'pass' data that comes with the first match
} else
console.log("error"); // no matches
Using ES6 Array#find is probably the easiest, but you could also do (among other things)
const x = [{
"id": "1",
"log": "1",
"pass": "1111"
}, {
"id": 2,
"log": "2",
"pass": "2222"
}, {
"id": 3,
"log": "3",
"pass": "3333"
}];
let myItem;
for (let item of x) {
if (item.log === '1') {
myItem = item;
break;
}
}
console.log(myItem);

Categories

Resources