nesting multiple level of array with associative - javascript

data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
how to format the above array into this
var name = {
"user": {
"name" : [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
}
}
I tried var name['name'] = data and don't know how to wrap the result. I want to wrap the result with 'user' as it assoc.

You can't assign properties as you create the object. Either first create the object and then set the property:
var name = {};
name.user = { name : data };
or create the entire object at once:
var name = { user: { name: data } };

var data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
var name = {
"user": {
"name" : data
}
}

Related

How can I add a key/value pair to a JavaScript object which is in an another object

I'm asking your help for the following code:
function vimeoImport() {
let videosToBeImported = [{
uri: "/videos/442638455",
name: "FOMME_1387_VD1",
modifed_time: "2020-07-29T09:24:48+00:00"
},{
uri: "/videos/442056086",
name: "FOMME_1387_VD2",
modifed_time: "2020-07-29T09:25:27+00:00"
},{
uri: "/videos/442638455",
name: "FOMME_2387_VD1",
modifed_time: "2020-07-29T09:24:48+00:00"
}];
let frtVideoUrlValues = {};
for (var index in videosToBeImported) {
var videos = videosToBeImported[index];
let videoName = videos.name;
let splitName = videoName.split('_');
let targetedVariationGroup = splitName[0].concat('_', splitName[1]);
let positionvideo = splitName[2];
let variationGroupParams = {};
variationGroupParams[positionvideo] = videos.uri;
if (targetedVariationGroup in frtVideoUrlValues) {
frtVideoUrlValues[targetedVariationGroup] += variationGroupParams;
} else {
frtVideoUrlValues[targetedVariationGroup] = variationGroupParams;
}
}
}
I tried to add a key/value pair (the key is a variable) in the targetedVariationGroup object which is in the frtVideoUrlValues object. When I try, I see the new key/value pair in the targetedVariationGroup but the merge is not functional and the 2 objects are not accessible:
And I try to obtain an object like this:
As, you didn't provide any output format, I am guessing the output should look like as follows(If this is not what you've wanted, pls provide proper output format):
{
FOMME_1387: [
{ VD1: '/videos/442638455' },
{ VD2: '/videos/442056086' }
],
FOMME_2387: [
{ VD1: '/videos/442638455' }
]
}
Now, to achieve this you should write code as follow:
function vimeoImport() {
let videosToBeImported = [
{
uri: "/videos/442638455",
name: "FOMME_1387_VD1",
modifed_time: "2020-07-29T09:24:48+00:00"
},
{
uri: "/videos/442056086",
name: "FOMME_1387_VD2",
modifed_time: "2020-07-29T09:25:27+00:00"
},
{
uri: "/videos/442638455",
name: "FOMME_2387_VD1",
modifed_time: "2020-07-29T09:24:48+00:00"
}
];
let frtVideoUrlValues = {};
for (var index in videosToBeImported) {
var videos = videosToBeImported[index];
let videoName = videos.name;
let splitName = videoName.split('_');
let targetedVariationGroup = splitName[0].concat('_', splitName[1]);
let positionvideo = splitName[2];
let variationGroupParams = {};
variationGroupParams[positionvideo] = videos.uri;
// here are the changes I've made
if(frtVideoUrlValues[targetedVariationGroup] === undefined) {
frtVideoUrlValues[targetedVariationGroup] = [];
}
frtVideoUrlValues[targetedVariationGroup].push(variationGroupParams);
}
console.log(frtVideoUrlValues);
}
vimeoImport();
The problem with your code is, you're using + to add object with another object, but + is only used to concat string in javascript. Instead of what you're doing, you should push objects into array. To add new elements in an array, you've to use push() method.
Also, notice, if key targetedVariationGroup in frtVideoUrlValues is undefined, I've assigned an empty array to targetedVariationGroup as follows:
frtVideoUrlValues[targetedVariationGroup] = [];
and then, pushed variationGroupParams object in the array as follows:
frtVideoUrlValues[targetedVariationGroup].push(variationGroupParams);

Seperate Objects in local storage Javascript

I currently have an item in local storage which looks like this
"cars":[
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}
I want to retrieve all of the Id's only and store them in a string.
At the minute I am pulling the data like this:
var cars = "";
cars= localStorage.getItem('cars');
var carArr= new Array();
carArr.push(cars);
How can I just obtain the Id's
If i understand your question correctly, you have to use Array.map to transform your array in combination with JSON.parse and JSON.stringify to read/write from the storage.
Here is an example using a "mocked" localStorage:
// use a mock storage because snippet doesn't allow localStorage usage.
var mockStorage = {};
// setup initial storage
try {
mockStorage.cars = JSON.stringify([
{
Id:7,
Name:"Audi",
},
{
Id:8,
Name:"Ford",
}
]);
} catch(e) {}
console.log('inital local storage:\n', mockStorage);
// example
var cars = [];
// parse JSON string value from storage to javascript object.
try {
cars = JSON.parse(mockStorage.cars)
} catch(e) {}
console.log('cars:\n', cars);
// transform array of cars to array of car ids
var ids = cars.map(car => car.Id)
console.log('car ids:\n', ids);
// transform array to JSON string
try {
mockStorage.cars = JSON.stringify(ids);
} catch(e) {}
console.log('local storage:\n', mockStorage);
localStorage only supports strings. So, you have to use JSON.parse to get the cars array from string and then use array#map to get all the ids.
var carsString = localStorage.getItem('cars');
var cars = JSON.parse(carsString);
var ids = cars.map( car => car.Id);
console.log(ids);
Use this,
//you get this from localStorage after you parse it
//JSON.parse(localStorage.cars);
var cars = [
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}];
var res = [];
cars.forEach(function(val){
res.push(val.Id);
});
console.log(res);

Create an array of Objects from JSON

I have a JSON file like below:
[
{"fields":{category_class":"CAT2",category_name":"A"},"pk":1 },
{"fields":{category_class":"CAT1",category_name":"B"},"pk":2 },
{"fields":{category_class":"CAT1",category_name":"C"},"pk":3 },
{"fields":{category_class":"CAT2",category_name":"D"},"pk":4 },
{"fields":{category_class":"CAT3",category_name":"E"},"pk":5 },
{"fields":{category_class":"CAT1",category_name":"E"},"pk":6 },
]
I want to create an array of objects from the above JSON which will have two properties. i) CategoryClass ii) CategoryNameList. For example:
this.CategoryClass = "CAT1"
this.CategoryNameList = ['B','C','E']
Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class. I tried this:
var category = function(categoryClass, categoryNameList){
this.categoryClass = categoryClass;
this.categoryList = categoryNameList;
}
var categories = [];
categories.push(new category('CAT1',['B','C','E'])
Need help.
You can use a simple filter on the array. You have a few double quotes that will cause an error in you code. But to filter only with CAT1 you can use the filter method
var cat1 = arr.filter( value => value.fields.category_class === "CAT1");
I would suggest this ES6 function, which creates an object keyed by category classes, providing the object with category names for each:
function groupByClass(data) {
return data.reduce( (acc, { fields } ) => {
(acc[fields.category_class] = acc[fields.category_class] || {
categoryClass: fields.category_class,
categoryNameList: []
}).categoryNameList.push(fields.category_name);
return acc;
}, {} );
}
// Sample data
var data = [
{"fields":{"category_class":"CAT2","category_name":"A"},"pk":1 },
{"fields":{"category_class":"CAT1","category_name":"B"},"pk":2 },
{"fields":{"category_class":"CAT1","category_name":"C"},"pk":3 },
{"fields":{"category_class":"CAT2","category_name":"D"},"pk":4 },
{"fields":{"category_class":"CAT3","category_name":"E"},"pk":5 },
{"fields":{"category_class":"CAT1","category_name":"E"},"pk":6 },
];
// Convert
var result = groupByClass(data);
// Outut
console.log(result);
// Example look-up:
console.log(result['CAT1']);
Question : Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class
Solution :
function Select_CatName(catclass,array){
var CatNameList=[]
$(array).each(function(){
if(this.fields.category_class==catclass)
CatNameList.push(this.fields.category_name)
})
return CatNameList;
}
This function return the Desired Category Name List, you need to pass desired catclass and array of the data , as in this case it's your JSON.
Input :
Above function calling :
Output :
Hope It helps.

javascript dynamic structure with array or object

Im trying to create a structure with Javascript as follows:
var users = {
user.id: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
user.id2: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
};
What i need: add new sessions and remove them, removing okay, but how should i define object and how can i push new sessions to user obejct? That's why key is equal to value.
If you want to use session.id1 instead of something like sessionId1 :
Assign value:
users['user.id'].['session.id1'] = value;
Create object:
var users = {
'user.id': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
'user.id2': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
};
But I don't recommend it. If you are the only one who is gonna work with this code, it's ok.
You can first create an empty object and fill it as and when the data comes like
users[user.id] = {};
For an example:
var users = {};
var user = {id : 1}; //Data received(Just an example)
users[user.id] = {};
var session = {id1 : 1.1}; //Data received
users[user.id][session.id1] = session.id1;
console.log(JSON.stringify(users));
How about refactoring the user object to store sessions as an array and push, pop and slice them as required.
var users = [
{
id:'userid',
sessions: [
{
id: 'sessionid',
sessiondata: something
},
{
id: 'sessionid',
sessiondata: something
}
]
}];
This way to can just use normal array operators on the session array for each user.

Populating Javascript Array of Objects with an embedded Array of Objects

I am new to Javascript (familiar with C/C++) and I am trying to parse out an XML file and store it in an Array of Objects. The structure is similar to a bullet list where there is one main List item and possibly multiple List subitems:
var MenuLine =
[{
label : "null",
icon : "null",
Subitem:
[{
label : "null",
icon : "null"
}]
}];
Which allows me to use the following syntax:
var someRandomSubitemText = MenuLine[2].Subitem[4].label;
I tried populating this array using the .push method:
var tempMenuLine = [];
var tempSubitem = [];
$(xml).find("item").each(function()
{
tempMenuLine.label = $(xml).children("label").text();
tempMenuLine.icon = $(xml).children("icon").text();
$(this).children("subitem").each(function()
{
tempSubitem.label = $(this).children("label").text();
tempSubitem.icon = $(this).children("icon").text();
tempMenuLine.Subitem.push(tempSubitem);
});
MenuLine.push(tempMenuLine);
});
However this does not work since the .push method passes a reference to tempMenuLine and I am overwriting tempMenuLine with each iteration. Is there a way that I could write directly to the MenuLine array using something similar to the following syntax?
$(xml).find("item").each(function(index1)
{
MenuLine[index1].label = $(xml).children("label").text();
MenuLine[index1].icon = $(xml).children("icon").text();
$(this).children("subitem").each(function(index2)
{
MenuLine[index1].Subitem[index2].label = $(this).children("label").text();
MenuLine[index1].Subitem[index2].icon = $(this).children("icon").text();
});
});
Move your temp var declarations inside of your loops:
$(xml).find("item").each(function() {
var tempMenuLine = [];
tempMenuLine[0].label = $(xml).children("label").text();
tempMenuLine[0].icon = $(xml).children("icon").text();
tempMenuLine[0].Subitem = []
$(this).children("subitem").each(function(){
var tempSubitem = [];
tempSubitem[0].label = $(this).children("label").text();
tempSubitem[0].icon = $(this).children("icon").text();
tempMenuLine[0].Subitem.push(tempSubitem);
});
MenuLine.push(tempMenuLine);
});
This way, you're initializing a new item for each iteration of the loops, removing the "link" it had to the previous item.
A recursive solution just for fun.
var MenuLine = Xml2Array(xmlText, 'item');
function Xml2Array(xmlDocument, itemName) {
if (!$(itemName, xmlDocument).length) {
return;
}
var tmpArray = [];
$(itemName, xmlDocument).each(function() {
tmpArray.push({
label: $('label', this).first().text(),
icon: $('icon', this).first().text(),
Subitem: Xml2Array(this, 'subitem')
});
});
return tmpArray;
}

Categories