How to get key "employee "
{
employee":{"name":"John","age":12}
}
It's not about Angular, this is plain Javascript:
const obj = { employee:{name:"John",age:12}}
const key = Object.keys(obj)[0]
You can use forEach to get your output if you use Array Object
function example1(array){
let res = [];
array = [{"ex1":{"name":"John1","age":12}}, {"ex2":{"name":"John2","age":12}}, {"ex3":{"name":"John3","age":12}}]
array.forEach((e, idx) => {
res.push(Object.keys(e))
})
document.getElementById("ex1").innerHTML = JSON.stringify(res);
}
<input type="button" value="example1" onclick="example1()">
<p id="ex1"></p>
if you just use only object you can use For...in to get your output
function example2(array){
let res = [];
obj = {"ex1":{"name":"John1","age":12}, "ex2":{"name":"John2","age":12}, "ex3":{"name":"John3","age":12}}
for(var val in obj){
res.push(val)
}
document.getElementById("ex2").innerHTML = JSON.stringify(res);
}
<input type="button" value="example2" onclick="example2()">
<p id="ex2"></p>
But remember when you put object or array or whatever check its valid or not. In your object is invalid here is the correct format
{"employee":{"name":"John","age":12}}
Related
There is an input field, Which has name metadata.country. The functionality is to get the name and split than make those index in square brackets ['metadata']['country']. I want to concatenate JSON and Index variables to get the country.The issue is when I try to join, it return [object Object].
Code:
//Input Fields (Html)
<input id="dataX" name="metadata.country">
<input id="dataY" name="metadata.city">
//Get ID
var inputField_Name = document.getElementById("dataX").attr['name'];
//JSON Data
var json = {name:"John",metadata:{country:"USA",city:"newyork"}};
//Split by dot
var targetName = inputField_Name.split('.');
//Convert them into square brackets
let copy='';
targetName.map(function(key, index) {
copy +="['"+key+"']";
});
//Response copy: ['metadata']['country']
console.log(json + copy);
//Response: [object Object]['metadata']['country']
Expected Response:
"USA"
//Don't want this method:
json [1];
Below snippet will help you find out the data from the object. Hope this helps
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
let copy='';
const data = targetName.reduce((result, targetKey) => result[targetKey] || {}, json)
console.log(data)
Below method can be used to update the value at the specified location without mutating the original object. you can get the data from the method and can use it to do setState.
let updateValue = (dataObj, keys, updatedValue) => {
let json = JSON.parse(JSON.stringify(dataObj));
let result = (keys ||[]).reduce((result, targetKey, index) => {
if(index === targetName.length - 1){
result[targetKey] = updatedValue;
return result[targetKey]
}
return result[targetKey] || {}
}, json)
return json;
}
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
const updatedJsonObj = updateValue(json, targetName, "CANADA")
console.group("Updated JSON");
console.log(updatedJsonObj)
console.groupEnd()
console.group("Original JSON");
console.log(json)
console.groupEnd()
You can try
JSON.stringify(json) + JSON.stringify(index)
var json = {name:"John",country:"USA"};
var index= ['1'];
console.log(JSON.stringify(json) + JSON.stringify(index));
You don't need to map through you can directly get the value from the object.
let inputField_Name = "metadata.country"
let json = {name:"John",metadata:{country:"USA"}};
let [meta, key] = inputField_Name.split('.');
let out= json[meta][key];
console.log(out)
Hi all I have problem to make some id into one array
Maybe you can help me...This image is the result
enter image description here
and this is my code
$.each(data.rows, function (i, ele) {
var tes = ele.ID;
console.log('ItemID', tes);
}
The Result that i want expect is each item in the one array like this 'ItemID = [22,2,43,2]'
const idArray = data.rows.map((r)=>r.ID)
//More verbose
const idArray = data.rows.map(function (ele){
return r.ID;
});
Map creates a loop through all the values in the array and uses the return of the function passed to create a new array.
EDIT:
I'm not sure I understand, you'd want an array of array?
const idArray = data.rows.map(function (ele){
return [r.ID];
});
var tempArray = []
$.each(data.rows, function (i, ele) {
tempArray.push(ele.ID);
}
// tempArray will be the solution
var data = [1,2,3,4]; // Assuming this array contains rows data
var resultArray = []; // Result array
var ids = data.map(function (ele){
return ele;
});
resultArray.push(ids.join(',')); // Join ids using "," separator
console.log(resultArray); // ["1,2,3,4"]
I have a few spans:
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />
And operations on them:
const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
if (typeof list[span.getAttribute('class')] === 'undefined') {
list[span.getAttribute('class')] = [];
}
list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});
console.log(list);
console.log(JSON.stringify(list));
But JSON.stringify return empty array.
How can I count the number of occurrences of data-id at a given SPAN the easiest way and next get it to string? I would like to send this data to API.
Fiddle: https://jsfiddle.net/x7thc59v/
here is a code that's working:
use object instead of array to have key.
use var instead of const to modify your variable;
const spans = document.querySelectorAll('span');
var list = {};
spans.forEach(function(span) {
if (typeof list[span.getAttribute('class')] === 'undefined') {
list[span.getAttribute('class')] = [];
}
list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});
console.log(list);
console.log(JSON.stringify(list));
If you want output like this [{"first":["1"]},{"second":["4","2"]},{"third":["5"]}]
Then you can follow this appraoch
const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
const className = span.getAttribute('class');
const valIndex = list.findIndex(val => val[className]);
const hasVal = valIndex !== -1;
if (className && hasVal) {
const preVal = list[valIndex][className];
list[valIndex][className] = preVal.concat(span.getAttribute('data-id'));
} else if (className && !hasVal){
list.push({[className]: [span.getAttribute('data-id')]});
}
});
console.log(list);
console.log(JSON.stringify(list));
Here is working jsfiddle;
The JSON.stringify function will not serialise string keys added to an array, only the numeric ones.
The trivial fix then is to replace const list = [] with const list = {} and then update the code that uses the results to expect an Object instead of an Array.
More generally, you should reduce the repetition in your code, especially the repeated calls to span.getAttribute('class'):
const spans = document.querySelectorAll('span');
const list = {};
spans.forEach(function(span) {
const cls = span.className;
const id = span.getAttribute('data-id');
list[cls] = list[cls] || []; // ensure the array exists
list[cls].push(id);
});
I think you wanted the list to be an object as the way you were trying to access the property of list by the class name.
Also rather than mutating an external object using forEach its better to use Array.prototype.reduce on the NodeList returned from document.querySelectorAll() call:
const spans = document.querySelectorAll('span');
//With Array.prototype.reduce
const list = Array.prototype.reduce.call(spans, function(acc, span) {
const attr = span.getAttribute('class');
const dataId = span.getAttribute('data-id');
acc[attr] ? acc[attr].push(dataId) : (acc[attr] = [dataId]);
return acc;
}, {});
console.log(list);
console.log(JSON.stringify(list));
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />
I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.
Code:
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
})
}
Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.
You can loop through the array and then through the object properties and make a new object using the colors as keys
var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}];
var new_response = {};
response.forEach(function(obj){
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = [];
new_response[obj[prop]].push(prop);
}
}
})
console.log(new_response);
The you can use the object for your needs as
new_response["red"]
giving you the list of all key with red value.
you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties.
So you can test the value and get keys for the value "yellow" or "red"
response.forEach(function(element) {
for (k in element) {
if (element[k]=="red" or element[k]=="yellow") {
// k is the key
}
}
});
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
for (i = 0; i < response.length; i++) { // iterate over response array
var item = response[i]; // get item from array
var key = Object.keys(item)[0]; // get the key of the item
var value = item[key]; // get the value of the item
if (value === 'yellow' || value === 'red') {
// do something, like adding it to a list
}
}
});
}
Given the following HTML form:
<form id="myform">
Company: <input type="text" name="Company" value="ACME, INC."/>
First Name: <input type="text" name="Contact.FirstName" value="Daffy"/>
Last Name: <input type="text" name="Contact.LastName" value="Duck"/>
</form>
What is the best way serialize this form in javascript to a JSON object in the format:
{
Company:"ACME, INC.",
Contact:{FirstName:"Daffy", LastName:"Duck"}
}
Also note that there might be more than 1 "." sign in the field name.
I think that what you'd do is this: for each input, first split the name at the separators (the '.' characters). Now, you have an array of names. You can then iterate through that array, making sure that your target "assembly" object (and sub-objects) have containers every time you come across a new name segment. When the array has 1 element in it, you simply add the value.
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
});
// ...
var object = $('#myform').extractObject();
I just sort-of made that up so there might be a bug or two; I can't remember whether all the browsers have "slice" but I think they do.
(edit: I forgot the all-important call to split())
You can loop through the form fields by name, use String#split to split the names on dot, and build up your resulting structure. Concept code:
function serializeDeep(form) {
var rv, obj, elements, element, index, names, nameIndex, value;
rv = {};
elements = form.elements;
for (index = 0; index < elements.length; ++index) {
element = elements[index];
name = element.name;
if (name) {
value = $(element).val();
names = name.split(".");
obj = rv;
for (nameIndex = 0; nameIndex < names.length; ++nameIndex) {
name = names[nameIndex];
if (nameIndex == names.length - 1) {
obj[name] = value;
}
else {
obj = obj[name] = obj[name] || {};
}
}
}
}
return rv;
}
Note that that doesn't allow for fields with repeated names (which should create arrays), nor does it elegantly handle a situation where you use the names "foo" and "foo.bar". But it should get you started.
I have managed it this way:
$('#Myform').attr('onsubmit', 'test()');
function test() {
var obj = {};
obj.title =$('#title').prop('value');
console.log('title: '+obj.title);
obj.website =$('#website').prop('value');
console.log('website: '+obj.website);
obj.tags =$('#tags').prop('value').split(',');
console.log('tags: '+obj.tags);
do_something(JSON.stringify(obj));
}
Of course this can be done if you know what the names are, and I am in fact generating the table itself using Formation plug-in.
I created an example for this question by using plain js, please check developer tool console to see the data object!
jsfiddle example
var data = {};
var array = 'person.name.first'.split('.');
var value = 'myFirstName';
generateObj(data, array, value);
console.log(data);
function generateObj(obj, arr, val) {
if (arr.length === 1) {
obj[arr[0]] = val
return;
}
var restArr = arr.splice(1);
if (!obj[arr[0]]) {
obj[arr[0]] = {};
}
generateObj(obj[arr[0]], restArr, val);
}
solution:
transform each name string to array.
iterate through each array.
recursively call a method which create an obj and set this obj as the value of the property and pass this obj to the next recursion.
Create an object of that shape then use a JSON encoder to write it out.