Find all keys inside array inside object of object - javascript

I have this object (i can not change it, it cames from an outside webservice) and I want to get all the ids, (structure inside data may change)
data: {
consoles:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
games:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
accesories:[
{
name:'',
id:''
},
{
name:'',
id:''
}
]
}
I was trying to get all the keys of the object with Object.keys(data) and after that do a for to try to print it
var keys = Object.keys(data);
for(var j = 0; j < keys.length; j++){
console.log(keys[j]);
for(var i = 0; i < data.keys[j].length; i++){
console.log(data.keys[j].id)
}
}

Try to replace the data.keys[j] with:
data[keys[j]]
So this gives you with:
var keys = Object.keys(data);
for(var j = 0; j < keys.length; j++){
console.log(keys[j]);
for(var i = 0; i < data.keys[j].length; i++){
console.log(data[keys[j]].id)
}
}

try this:-
var productsKeys = Object.keys(data);
for(var j = 0; j < productsKeys.length; j++){
for(var i = 0; i < data[productsKeys[j]].length; i++){
console.log(data[productsKeys[j]][i].id)
}
}
Demo

for(var i=0; i<data.consoles.length;i++){
console.log( data.consoles[i].id);
}
for(var i=0; i<data.games.length;i++){
console.log( data.games[i].id);
}
for(var i=0; i<data.accessories.length;i++){
console.log( data.accessories[i].id);
}
If consoles,games,accessories arrays have laways the same length we can use only one for.

here is what my try is how can you achieve this
data = {
consoles:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
games:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
accesories:[
{
name:'',
id:''
},
{
name:'',
id:''
}
]
}
$.each(data,function(key,val){
$.each(data[key],function(k,v){
$.each(v,function(kf,vf){
console.log(kf + "---->" + vf);
});
});
});

Related

Failed to console unique names from JSON array

I have a JSON array having hundreds of objects where each JSON object having name and hobbies property.
Below is the JSON structure:
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
So here if I will iterate through this data it will give me same name multiple times wherever multiple hobbies are present.So if I am console it result would be
Paul,Football
Paul,Reading
Riya,Singing
Riya,Dancing
Jack,Gaming
I don't want above output I want wherever there is same name is coming in a same object don't console it like below:
Paul,Football
"",Reading
Riya,Singing
"",Dancing
Jack,Gaming
Below is my code:
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
const example = (data) => {
for(var i=0;i<data.length;i++){
for(var j=0;j<data[i].hobbies.length;j++){
console.log(data[i].name,data[i].hobbies[j]);
if(i=0){
console.log(data[i].name,data[i].reports[j]);
}
else{
const prev = i-1;
if(data[prev].name == data[i].name) { //Getting TypeError here cannot read property 'name' of undefined
console.log("",data[i].reports[j]);
}
else{
console.log(data[i].name,data[i].reports[j]);
}
}
}
}
}
example(data);
In above code I am trying to compare the previous value of name in data array with the current value of name. If it's same then making name field " " else putting name value and for first element for position 0 I am putting value as it is.
Why am I getting this TypeError?
There are several issues, first is typo, you assigned instead of comparing
if (i=0) {
// ^^^^^
console.log(data[i].name,data[i].reports[j]);
}
The rest is logic, all you have to do is to check the index of j
const example = data => {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].hobbies.length; j++) {
if (j == 0) {
console.log(data[i].name, data[i].hobbies[j])
} else {
console.log("", data[i].hobbies[j])
}
}
}
}
Full solution
const data = [
{
name: "Paul",
hobbies: ["Football", "Reading"],
},
{
name: "Riya",
hobbies: ["Singing", "Dancing"],
},
{
name: "Jack",
hobbies: ["Gaming"],
},
]
const example = data => {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].hobbies.length; j++) {
if (j == 0) {
console.log(data[i].name, data[i].hobbies[j])
} else {
console.log("", data[i].hobbies[j])
}
}
}
}
example(data)
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
data.forEach(d => {
d.hobbies.forEach((hobby, index) => {
const name = index == 0 ? d.name : '""'
console.log(name + ',' + hobby)
})
})
Just print the name if index of hobby is 0

How can I delete all objects in a json array by its keyword

I have json like this:
json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
]
What I need is to delete value2 so the json would look like:
json = [
{
"value1":"3863"
},
{
"value1":"4456"
},
{
"value1":"98494"
},
]
I have tried to use
for(var i = 0; i < json.length; i++)
{
delete json["value2"];
}
but it doesn´t work.
Is there any way of doing that ?
const json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
];
json.forEach(item => delete item.value2);
use map.
json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
}
];
console.log(json.map(({value1}) => ({value1})));
With your current syntax:
for(var i = 0; i < json.length; i++)
{
delete json[i].value2;
}
You just have missed i usage in accessing json array elements:
for(var i = 0; i < js.length; i++)
{
delete json[i]["value2"];
}
You forgot the iterator i:
delete json[i]["value2"];
var json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
];
for(var i = 0; i < json.length; i++) {
delete json[i]["value2"];
}
console.log(json);

How can I resize Jira gadgets' data?

I am implementing a Jira gadget. I have an problem about retrieve data.
I am retrieving data from DB to gadget. There are lots of columns so the gadget cannot show all columns. I guess I have to resize data. There is one more thing; how can I stop the retrieving data to go end of pages?
Here is my gadget.xml
#requireResource("com.atlassian.gadgets.publisher:ajs-gadgets")
#requireResource("sqlGadget:Web-resources")
#requireResource("com.atlassian.jira.gadgets:common")
#requireResource("com.atlassian.jira.gadgets:autocomplete")
#includeResources()
<script type="text/javascript">
(function () {
var gadget = AJS.Gadget({
baseUrl: "__ATLASSIAN_BASE_URL__",
useOauth: "/rest/gadget/1.0/currentUser",
config: {
descriptor: function(args) {
var gadget = this;
gadgets.window.setTitle("SQL Gadget Config");
var projectPicker = AJS.gadget.fields.projectPicker(gadget, "projectId", args.projectOptions);
return {
fields: [
projectPicker,
{
id: "configNumber-id",
userpref: "configNumber",
label: "Config number",
description: "",
type: "select",
selected: gadget.getPref("configNumber"),
options: [
{
label:"1",
value:"1"
},
{
label:"2",
value:"2"
},
{
label:"3",
value:"3"
}
]
},
AJS.gadget.fields.nowConfigured()
]
};
},
args: function()
{
return [
{
key: "projectOptions",
ajaxOptions: "/rest/gadget/1.0/filtersAndProjects?showFilters=false"
}
];
}()
},
view: {
/* HTML PART*/
onResizeAdjustHeight: true,
enableReload: true,
template: function (args)
{
var gadget = this;
var response = args.projects.value;
AJS.$.each(AJS.$.parseJSON(response), function(idx, obj) {
console.log(obj);
});
var myList=AJS.$.parseJSON(response);
var test="<body onLoad=buildHtmlTable()><table id=excelDataTable border=1> </table></body>";
document.getElementById("myDiv").innerHTML = test;
var columns = addAllColumnHeaders(myList);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = AJS.$('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append(AJS.$('<td/>').html(cellValue));
}
AJS.$("#excelDataTable").append(row$);
}
function addAllColumnHeaders(myList)
{
var columnSet = [];
var headerTr$ = AJS.$('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if (AJS.$.inArray(key, columnSet) == -1){
columnSet.push(key);
headerTr$.append(AJS.$('<th/>').html(key));
}
}
}
AJS.$("#excelDataTable").append(headerTr$);
return columnSet;
}
},
args: [
{
key: "projects",
ajaxOptions: function ()
{
var projectName;
var confOrder;
var projectField = document.getElementById("projectId");
var confNumbElement = document.getElementById("configNumber-id");
if(projectField != null){
projectName = projectField.options[projectField.selectedIndex].text;
console.log(projectName);
}
if(confNumbElement != null){
confOrder = confNumbElement.options[confNumbElement.selectedIndex].text;
console.log(confOrder);
this.configNumber = confOrder;
}
return {
url: "/rest/sqlrestsource/latest/execute",
data: {
projectId : gadgets.util.unescapeString(this.getPref("projectId")),
configNumber : gadgets.util.unescapeString(this.getPref("configNumber")),
}
};
}
}
]
}
});
})();

array.push to an array within an array

I'm trying to push JSON data to an array within an array. The problematic difference to other examples of this I can find is that both arrays are being built by a loop which I believe is the reason for the error I'm receiving. TypeError: Cannot call method 'push' of undefined
Here's a somewhat minimal example of what I'm trying to achieve.
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
json.trips.push({departure: departure, arrival: arrival, nodes: []});
for (var j = 0; j < data.trips[i].legs.length; j++) {
json.trips.nodes.push({test: 'test'});
}
}
The output I'm trying to create should be looking like this.
{
origin: origin,
destination: destination,
trips: [
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
},
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
}
]
}
The test nodes are nonsensical, sure, but shouldn't adding them in this way be possible?
The line:
json.trips.nodes.push({test: 'test'});
should be:
json.trips[i].nodes.push({test: 'test'});
json.trips.nodes is indeed undefined. I believe you want to add it to the new item in the trip loop?
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var newNode = {
departure: data.trips[i].dep.time,
arrival: data.trips[i].arr.time,
nodes: []
};
for (var j = 0; j < data.trips[i].legs.length; j++) {
newNode.nodes.push({test: 'test'});
}
json.trips.push(newNode);
}
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
var trip = {departure: departure, arrival: arrival, nodes: []}
for (var j = 0; j < data.trips[i].legs.length; j++) {
trip.nodes.push({test: 'test'});
}
json.trips.push(trip);
}

JavaScript. Extract values from associative array

How can I get the values from this associative array in JavaScript?
I just need the email addresses and not the labels.
(
{
office = ("my#email.com");
home = ("ahome#anotheremail.com");
work = ("nothing#email.com");
},
{
home = ("test#test.se");
}
)
UPDATE: Prefered output in JSON would be:
{
"data": [
{
"email": "my#email.com"
},
{
"email": "ahome#anotheremail.com"
},
{
"email": "nothing#email.com"
},
{
"email": "test#test.se"
}
]
}
Thankful for all input!
What you probably meant to do is:
var x = [{
office: ("my#email.com"),
home: ("ahome#anotheremail.com"),
work: ("nothing#email.com")
},
{
home: ("test#test.se")
}]
and:
for(var j = 0; j < x.length; j++)
{
for(var anItem in x[j])
{
console.log(x[j][anItem])
}
}
// EDIT:
however, it's not the best practice to use for … in.
Maybe you could change your data structure to:
var x = [[{
value: "my#email.com",
type: "office"
},
{
value: "ahome#anotheremail.com",
type: "home"
},
{
value: "nothing#email.com",
type: "work"
}],
[{
value: "test#test.se",
type: "home"
}]];
and iterate over using:
for( var i = 0, xlength = x.length; i < xlength; i++ )
{
for( var j=0, ylength = x[i].length; j < ylength; j++ )
{
console.log(x[i][j].value);
}
}
Here's a one-liner:
console.log(Object.keys(assoc).map(k => assoc[k]));
where assoc is your associative array.
Edit
I have a better answer here.
You can 'foreach' over the object to get it's properties:
for(var j = 0; j < mySet.length; j++)
{
for(var propName in mySet[j])
{
var emailAddress = mySet[j][propName];
// Do Stuff
}
}
Answer for edited question:
var ret = {data: []};
for(var j = 0; j < x.length; j++)
{
for(var anItem in x[j])
{
ret.data.push({
email: x[j][anItem]
});
}
}
console.log(ret);
The result is kept in ret.
Is it your input in JSON format? Because if so, it's the wrong syntax. However
let _in = [
{
office : "my#email.com",
home : "ahome#anotheremail.com",
work : "nothing#email.com",
},
{
home : "test#test.se"
}
]
let _out = []
_in.forEach( record => {
_out = _out.concat(Object.values(record).map(x => new Object({email : x})))
})
console.log(_out)
for each record I extracted values and "packed" into an object with the "email" attrbiute, then I merged all those arrays obtained from the original array of records
It seems that you're looking for Object.values.

Categories

Resources