call javascript object properties [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is probably a very easy question but let's say I have a php json_encoded javascript object of this form:
var js_objet = {
"1": {
"Users": {
"id": "14",
"name": "Peter"
},
"Children": [
{
id: 17,
name: "Paul"
},
{
id: 18,
name: "Mathew"
}
]
}
}
What is the synthax to get the name of the child with id 18 (Mathew) for example from that Object?
Thank you

Here's such a custom function as mentioned earlier.
function getChildrenById(id){
for (var child in js_objet[1].Children){
if(id == js_objet[1].Children[child].id){
return js_objet[1].Children[child].name;
}
}
return false;
}
running getChildrenById(18) would return "Mathew"
Hope that helps,
R.

You can do it like this:
var name = js_objet["1"].Children[1].name;
JSFiddle available here

This is how I would approach this problem:
var id = 18;
var name = '';
var jsObjIndex = "1";
var jsObjAttr = "Children"
for (var i = 0; i < js_objet[jsObjIndex][jsObjAttr].length; i++)
{
if (js_objet[jsObjIndex][jsObjAttr][i].id == id)
{
name = js_objet[jsObjIndex][jsObjAttr][i].name;
break;
}
}
You are basically performing a linear search on every element of jsObjIndex.Children. There are likely better solutions however :).

This really is a comment, but I don't have enough reputation (but it's relevant as I recently encountered the same issue): This would probably be easier to do if you can change the JSON format to use the ID as the key for each child object:
var js_objet = {
"1": {
"Users": {
"id": "14",
"name": "Peter"
},
"Children": {
"17":{
"name": "Paul"
},
"18":{
"name": "Mathew"
}
}
}
}
Then you can simply call it using
js_objet[1].Children[18].name;
This is assuming each ID is unique.

Related

How to get keys from json object in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a json file:
[
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
}, {
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}]
Now I want to get a list of the keys of each "name" object. At the end there should be ths list
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
and save it into an array.
What i have tried
var mydata = JSON.parse("jsonstring").ingredients;
hope this is understanable?
for each data in the array (map)
you want the ingredient part (.ingredients),
extract the keys (Object.keys)
and flatten the array (.flat())
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
You may prefer loop style. the only difference is flattening occurs with ... operator.
var results = [];
for (let a of array) {
results.push(...Object.keys(a.ingredients))
}
My proposition is :
'use strict'
const array = [
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
},
{
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}
]
const mydata = array.map((val) => {
return Object.keys(val.ingredients);
}).flat();
console.log(mydata)
// expected output: Array ["rum", "coke", "gin", "tonic"]
// Now you can get :
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
Hope that help you? Thank

Restructure data from array with javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I hope it is not a stupid question. My array looks like this:
const data = [
{
pollType: "1",
pollName: "Can you help me?",
options: [
{ Options: "Yes, I can", PID: "oFnxh-NDdcP" },
{ Options: "No way!", PID: "d9A10-omlUd" }
]
}
];
But I need to have it:
const result = [
{
pollType: "1",
pollName: "Can you help me?",
option1: "Yes, I can",
pid1: "oFnxh-NDdcP",
option2: "No way!",
pid2: "d9A10-omlUd"
}
];
Please don't get angry if it is so simple to do. I highly appreciate your help and if you do a an example so myself and other people can find it very useful in a future...
var orig = [{"pollType":"1","pollName":"Can you help me?","options":[{"Options":"Yes, I can","PID":"oFnxh-NDdcP"},{"Options":"No way!","PID":"d9A10-omlUd"}]}]
var newArr = [];
orig.forEach(v => {
var newObj = {};
newObj.pollType = v.pollType;
newObj.pollName = v.pollName;
v.options.forEach((k, i) => {
newObj["options" + (i + 1)] = k.Options;
newObj["pid" + (i + 1)] = k.PID;
});
newArr.push(newObj);
});
console.log(newArr);

I need help converting this array of objects into an array of arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following array of objects:
[
{
"messages": {
"m1": {
"message": "Relay malfunction found. Cause: moth.",
"sender": "ghopper"
}
},
"title": "Historical Tech Pioneers",
"key": "one"
} ]
But I wish to convert it to an array of arrays. For example: I want to turn the title field below:
"title": "Historical Tech Pioneers"
Into:
"title": [ "Historical Tech Pioneers" ]
Thank you for your help
Assuming the declaration:
var myArr = [
{
"messages": {
"m1": {
"message": "Relay malfunction found. Cause: moth.",
"sender": "ghopper"
}
},
"title": "Historical Tech Pioneers",
"key": "one"
}
];
You can iterate over each element and reassign the property using:
myArr.forEach(o => o.title = [o.title]);
Or without ES6:
myArr.forEach(function (o) {
o.title = [o.title]);
});

Find specific key/value in array of objects and print out another key/value in that object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have this response from a $.getJSON call. Now I want to select the name property of the object with "selected": true, and print it to a div with id charTitle.
"titles": [{
"id": 17,
"name": "Sergeant %s"
}, {
"id": 53,
"name": "%s, Champion of the Naaru"
}, {
"id": 64,
"name": "%s, Hand of A'dal",
"selected": true
}]
You can achieve this with a simple loop:
for (var i = 0; i < obj.titles.length; i++) {
if (obj.titles[i].selected) {
$('#charTitle').text(obj.titles[i].name);
}
}
Example fiddle
Or with jQuery's $.each():
$.each(obj.titles, function(i, title) {
if (title.selected)
$('#charTitle').text(title.name);
});
Note that if you have multiple objects in the array with selected set to true you would need to use append() instead of text() to set the content of the div, otherwise the previous value will be overwritten.
using underscore you can get this with
var titles = ...
_.findWhere(titles, {selected: true});
see http://underscorejs.org/#findWhere
Try using Array.prototype.filter()
var arr = [{
"id": 17,
"name": "Sergeant %s"
}, {
"id": 53,
"name": "%s, Champion of the Naaru"
}, {
"id": 64,
"name": "%s, Hand of A'dal",
"selected": true
}]
var res = arr.filter(function(val, key) {
return val.selected === true
})[0].name;
$("#charTitle").html(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="charTitle"></div>

Iterate json data in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Following JSON data comes from php,
I have tried following code. But console displays undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj.city);
});
EDIT : Also it's not working and throwing undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj[0].city);
});
It is working : console.log(result.address.address1.city);. But in this case address1 is not fixed. eg. result.address.xyz.city, result.address.abc.city
You're calling city on each address, while cities are inside addressX inside address. Try:
jQuery.each(result.address, function(key, val) {
console.log(val.city);
});
jsfiddle DEMO
Maybe in this way:
for (i = 0; i < result.address.length; i++) {
console.log(result.address[i].city);
}
I'm not sure if jquery.each works in this case.
I hope it helps.
Javascript
var dictionary = {
"12Jan2013": [{
"id": "0",
"name": "ABC"
}, {
"id": "1",
"name": "DEF"
}],
"13Jan2013": [{
"id": "0",
"name": "PQR"
}, {
"id": "1",
"name": "xyz"
}]
};
for (var i in dictionary) {
dictionary[i].forEach(function(elem, index) {
console.log(elem, index);
});
}
Output
Object {id: "0", name: "ABC"} 0
Object {id: "1", name: "DEF"} 1
Object {id: "0", name: "PQR"} 0
Object {id: "1", name: "xyz"} 1

Categories