I am trying to return my JSON object's properties. My JSON file object looks like:
{ Products:
{
'Cars': { tableFields: [Object] },
'Planes': { tableFields: [Object] }
}
}
I am trying to return an array that contains Products' attributes - Cars and Planes. For example - I want the end result to be the following array:
['Cars', 'Planes']
Can someone help?
Thanks!
You can use Object.keys() function:
var data = {
Products: {
'Cars': {
tableFields: [ Object ]
},
'Planes': {
tableFields: [ Object ]
}
}
};
var result = Object.keys(data.Products);
console.log(result);
var keys = [];
for ( var key in Products )
{
//We only want the direct properties
if ( Products.hasOwnProperty( key ) ) keys[ keys.length ] = key;
}
Related
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 add attribute to the root of JSON object consists of array of objects?
If my JSON object something like that:
[
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
]
I do the following:
worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
And make sure that the jQuery fetching data from the inputs but this doesn't work.
This will change property of all object in array if you want to change in particular then use index for this for exp->
worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
var worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON = worktimeJSON.map(function(val){
val.Id = $('.Js-WorkTime-id').val();
val.Name = $('.Js-WorkTime-name').val();
val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
return val;
});
Push can do the job.
let worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON.push
({
id: "someID",
name: "toto",
WorkTimeRegulationId: 42
});
console.log(worktimeJSON);
I structure my object like this:
let WorkTimeRegulationViewModelJSON = {
Id: $('.Js-WorkTimeRegulation-id').val(),
Name: $('.Js-WorkTimeRegulation-name').val(),
NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
AssignedWorkTimes: JSON.parse(worktimeJSON)
};
I am using API that its response contains dynamic array of strings as the following:
var arr = ["Request.name","Request.name.first","Request.name.first.last"]; //response 3
so i want to convert it dynamically to array of JSON objects like this:
var arrayOfObjects = [
{
"Request": {
"name":val
}
} //converted from arr[0]
,{
"Request": {
"name":{
"first":val
}
}
} //converted from arr[1]
,{
"Request": {
"name":{
"first":{
"last":val
}
}
}
} //converted from arr[2]
];
and so on...
is this possible?
You can create a function that converts a dot-separated string into a respective deeply nested object, then map your input array of strings with it. My solution is iterative, though I think it can be done recursively as well.
var arr = ["Request.name","Request.name.first","Request.name.first.last"];
function createObjFromStr(str) {
return str.split('.').reduceRight((all, key, i, arr) => {
if (i === arr.length - 1) {
all = {[key]: 0};
} else {
all[key] = Object.assign({}, all);
Object.keys(all).forEach(k => {
if (k !== key) delete all[k];
});
}
return all;
}, {});
}
const arrayOfObjects = arr.map(createObjFromStr);
console.log(arrayOfObjects);
I have a JSON object that contains two arrays. I want to convert those array elements into individual elements in the JSON object.
I need this for an input into a D3 function in javascript.
My object now:
{
0:{
start:"2016-01-01",
values:[10,11,12],
names:["a","b","c"]
},
1:{
start:"2016-01-02",
values:[25,23,50],
names:["a","b","c"]
}
}
Converted object:
{
0:{
start:"2016-01-01",
a:10,
b:11,
c:12
},
1:{
start:"2016-01-02",
a:25,
b:23,
c:50
}
}
The number of variables can vary. It won't always be 3.
Any help appreciated, Thanks
var array = {
0:{
start:"2016-01-01",
values:[10,11,12],
names:["a","b","c"]
},
1:{
start:"2016-01-02",
values:[25,23,50],
names:["x","y","z"]
}
}
convertArrayProp = ( newObject ) => {
Object.keys( array ).map( ( key ) => {
newObject[key] = {};
newObject[key]['start'] = array[key]['start'];
array[key]['names'].map( ( name, index ) => newObject[key][name] = array[key]['values'][index]);
});
return newObject;
}
console.log(convertArrayProp({}));
I know this not the best but this is one of the way to achieve what you want.
x={
0:{
start:"2016-01-01",
values:[10,11,12],
names:["a","b","c"]
},
1:{
start:"2016-01-02",
values:[25,23,50],
names:["a","b","c"]
}
}
for(y in x){
if(x.hasOwnProperty(y)){
x[y].names.forEach((key, i) => x[y][key] = x[y].values[i]);
delete x[y].names;
delete x[y].values;
}
}
console.log(x);
I have been doing some sorting and still dont get it why the result is []. could you guys help me out what im missing?
I have my raw array object:
var data = [
{message:'hello', username:'user1'},
{message:'data', username:'user1'},
{message:'sample', username:'user2'},
{message:'here', username:'user2'},
];
my function is:
var chat = [];
function reorder(obj) {
obj.forEach( function(val, i) {
if(typeof chat[val.username] === 'undefined') {
chat[val.username] = [];
chat[val.username].push(val);
}
else
chat[val.username].push(val);
});
return chat;
}
and on my console:
reorder(data);
I am expecting to have:
var data2 = [
'user1': [{message:'hello', username:'user1'}, {message:'data', username:'user1'} ],
'user2': [{message:'sample', username:'user2'}, {message:'here', username:'user2'} ],
];
You can do this easily with reduce:
var data2 = data.reduce(function(acc, x) {
acc[x.username] = (acc[x.username] || []).concat(x)
return acc
},{})
/*^
{ user1:
[ { message: 'hello', username: 'user1' },
{ message: 'data', username: 'user1' } ],
user2:
[ { message: 'sample', username: 'user2' },
{ message: 'here', username: 'user2' } ] }
*/
The problem is that you made chat an array. When you look at an array in the console, it only displays the numeric indexes, not the named properties; you have to use console.log(chat) to see the named properties.
Since you want this to be an object with named properties, you should declare it as an object, not an array:
var chat = {};
Use Underscore's _.groupBy:
_.groupBy(data, 'username')