How to get these key in JavaScript object - javascript

I have the following object:
var input = {
"document": {
"people":[
{"name":"Harry Potter","age":"18","gender":"Male"},
{"name":"hermione granger","age":"18","gender":"Female"}
]
}
}
I do like this :
_.each(result.document[people], function(item){
console.log(item);
//What should I do here ? or I come wrong way ?
});
And in item I get :
{name : 'Harry Potter', age : '18':, gender:'Male'}
{name : 'hermione grange', age : '18':, gender:'Female'}
I would like to get [name,age,gender]. What should I do?

If you think your values are dynamic use a function first
var input = {
"document": {
"people":[
{"name":"Harry Potter","age":"18","gender":"Male"},
{"name":"hermione granger","age":"18","gender":"Female"}
]
}
}
var func = function (one, two) {
var array = input[one][two];
var arr =[];
for (var i=0; i<array.length; i++){
arr = Object.keys(array[0]);
}
return arr;
}
func("document", "people"); // will return ["name", "age", "gender"]

Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]

Something like this?
_.each(result.document[people], function(item) {
_.each(item, function(item, key) {
console.log(key);
});
});
_.each sends in a second key parameter to the callback function in the case of objects.

OK, Now I know you actually want the name of object, not the value. So I add another code for you.
I'm sorry I don't have time to explain now, but this code I wrote does the trick you need.
This shows the name of object:
root_obj=input.document.people[0];
tmp=[];
for(val in root_obj )
{
tmp.push(val);
}
console.log(tmp);
This shows the value of object:
root_obj=input.document.people;
for(obj in root_obj )
{
tmp=[];
for(val in root_obj[obj] )
{
tmp.push(root_obj[obj][val]);
}
console.log(tmp);
}

Here you go.. Final answer. (edited to return keys instead of values as per comment)
_.each(result.document[people], function(item){
//get keys as numerical array
var num_arr = [];
for (var key in item) {
num_arr.push( key );
}
console.log(num_arr); // should return ['name', 'age', 'gender']
});

Related

Push content of the object to array instead of the name of object

I have an empty object, and i want to push a key value pair to the array.
required.forEach(function(value){
if(value){
var tempVal = "event_info.schema." + value;
// console.log(tempVal);
var row = {tempVal: [properties[value]['type']]};
}
});
when I console.log(row) it shows
{ tempVal: [ 'string' ] }
However I want it to be the content of tempVal instead of "tempVal"
i.e. if tempVal = "name", I want row to be { name : ['string']}. How can I achieve this?
I have tried tempVal.eval() but that is an error. Can you point me to the right direction. Thanks in advance.
Objects can also be indexed with brackets.
tempVal = 'someString';
var obj = {};
obj[tempVal] = ['myArrayOfOneString'];
console.log(obj) // {'someString': ['myArrayOfOneString']}
Note that obj.something is equivalent to object['something']
This should do what you are looking for:
var
event_info = {
schema: {
name: "Yoda",
age: "150"
}
},
properties = {
name: {type: "male"},
age: {type: "old"}
}
//
var value = "name";
//
var tempVal = event_info.schema[value];
var row = {};
row[tempVal] = [properties[value]['type']];
console.log("tempVal:", tempVal);
console.log("row:", row);
console.log("row 'Yoda':", row["Yoda"]);
you will have to use array notation to set the property dynamically, like this:
var row = {};
row[tempVal] = [properties[value]['type']];
EDIT: as a commenter pointed out, you can condense this to one line (ES6 only):
var row = {[tempVal]: [properties[value]['type']]}

Remove all elements from object except specified key?

I have an object:
"languages": {
"en":["au", "uk"],
"de":["de"],
....
}
How can I remove everything but a specified key, so if I specify 'en' I just want an object that contains "en":["au", "uk"]
General solution for the original question of 'how do I remove all keys except specified keys' (refined from Rajaprabhu's answer):
validKeys = [ 'a', 'b', 'c' ];
userInput = { "a":1, "b":2, "c":3, "d":4, "e":5 }
Object.keys(userInput).forEach((key) => validKeys.includes(key) || delete userInput[key]);
Simply, you could create a new object with specified field;
var key = 'en';
var o = {
"languages": {
"en": ["au", "uk"],
"de": ["de"]
}
}
var res = {}
res[key] = o.languages[key];
Try to delete the unwanted properties,
var obj = { "languages": { "en":["au", "uk"],"de":["de"] }};
Object.keys(obj.languages).forEach(function(itm){
if(itm != "en") delete object.languages[itm];
});
A simple loop using delete will do it.
var key = 'en';
for (var k in obj.languages) {
if (obj.languages.hasOwnProperty(k) && k != key) {
delete obj.languages[k];
}
}
Was searching for the answer and the previous ones helped me, just adding a functional version of the code that I needed:
function returnNewObjectOnlyValidKeys(obj, validKeys) {
const newObject = {};
Object.keys(obj).forEach(key => {
if (validKeys.includes(key)) newObject[key] = obj[key];
});
return newObject;
}

Parsing JSON to a regular JavaScript array

How can I load a regular array from a JSON Response like this:
{"project":"8","powerline":"188.396496","road":"7.876766","cost":"69885005.45"}
to
var cars = [8, 188.396496, 7.876766, 69885005.45];
I already tried something like this:
req.done(function(data) {
var cars = JSON.parse(data);
});
but it is not doing the job.
You can simply run a for..in loop like this. and keep pushing the values into a new array.
var obj = {
"project" : "8",
"powerline" : "188.396496",
"road" : "7.876766",
"cost" : "69885005.45"
}
var arr = [];
for (var key in obj) {
var val = parseFloat("0" + obj[key]);
arr.push(val)
}
You can manipulate JSON object as Array, please try this way
req.done(function(data) {
var cars = $.map(JSON.parse(data), function(value, index){
return i;
});
console.log(cars);
});
That's because you're getting an object when you're calling JSON.parse. You can run the following to get the values without keys:
req.done(function (data) {
var jsonData = JSON.parse(data),
cars = []
for (var key in jsonData) {
cars.push(jsonData[key])
}
})

create an associative array in jquery

This is what I have so far and the shoe types are boots, wellingtons, leather, trainers (in that order)
I want to iterate through and assign the value so I haves something like
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
at the moment I just get an array of {3,0,1,3} which I can work with but it is not very helpful.
function shoe_types() {
var shoeArray = [];
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray.push ( parseInt($(this).val()) );
});
return shoeArray;
}
Check this function
function shoe_types() {
var shoeArray = {}; // note this
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray[$(this).attr('id')] = parseInt($(this).val()) ;
});
return shoeArray;
}
PS: Assuming $(this).attr('id') has all the shoe types
Associative array in javascript is the same as object
Example:
var a = {};
a["name"] = 12;
a["description"] = "description parameter";
console.log(a); // Object {name: 12, description: "description parameter"}
var b = [];
b["name"] = 12;
b["description"] = "description parameter";
console.log(b); // [name: 12, description: "description parameter"]
What you want is a function that will return an object {}
LIVE DEMO
function shoe_types(){
var shoeObj = {};
$('[name="number"]').each(function(){
shoeObj[this.id] = this.value;
});
return shoeObj;
}
shoe_types(); // [object Object]
You can try this to create an associate array in jquery
var arr = {};
$('[type=number]').each(function(){
arr.push({
$(this).attr('id'): $(this).val()
});
});
console.log(arr);
This will allow you to send your all data whatever you want to pass in array by ajax.
if $(this).attr('id') is the type of shoes you can try that
shoeArray[$(this).attr('id')] = parseInt($(this).val());

In Javascript, how can I Rename/Renumber a set of properties?

This is one of those questions I'm ashamed to even ask, but I'm working with an external JSON source and I'm forced to do something ugly. So here goes...
I have 'dirty' Javascript object, with property names containing a number at their end:
{ "Friend1" : "Bob",
"Friend6" : "Fred",
"Friend632" : "Gonzo",
"FriendFinder1" : "Dolly",
"FriendFinder4294" : "Jan"
}
I'm trying to figure out a way to clean-up/"zero-index" these property names so the object would look like:
{ "Friend0" : "Bob",
"Friend1" : "Fred",
"Friend2" : "Gonzo",
"FriendFinder0" : "Dolly",
"FriendFinder1" : "Jan"
}
I'm referencing this indexOf/Regex code:
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Any strategies you could recommend for doing this? I'll post where I'm at in a bit. Many thanks!
Take the "base" of a key and append items with a common base to an array using the original index. (This produces a sparse array.) Then stretch it out again by enumerating each item with a common base into a new key with 'base'+enumeratedindex.
The trick here is to use a method like forEach to enumerate the array--this will only visit assigned items in a sparse array, allowing you to determine the sort order just by using the original index-part of the key.
If you don't have access to forEach, you can accomplish a similar task by including the key in the array items. Instead of an intermediate array like this:
{Friend: [undefined, "Bob", undefined, undefined, undefined, undefined, "Fred"]}
You have one like this:
{Friend: [[6, 'Fred'],[1, 'Bob']]}
Then you sort the array and visit each item in a foreach loop, extracting the second item.
Here is code:
function rekey(obj) {
var rekey = /^(.*?)(\d+)$/;
var nestedobj = {}, newobj = {};
var key, basekeyrv, newkey, oldidx, newidx;
function basekey(key) {
return rekey.exec(key).splice(1);
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
basekeyrv = basekey(key);
newkey = basekeyrv[0];
oldidx = parseInt(basekeyrv[1], 10);
if (!nestedobj[newkey]) {
nestedobj[newkey] = [];
}
nestedobj[newkey][oldidx] = obj[key];
}
}
for (key in nestedobj) {
if (nestedobj.hasOwnProperty(key)) {
newidx = 0;
nestedobj[key].forEach(function(item){
newobj[key+newidx++] = item;
});
}
}
return newobj;
}
rekey({
"Friend1" : "Bob",
"Friend6" : "Fred",
"Friend632" : "Gonzo",
"FriendFinder1" : "Dolly",
"FriendFinder4294" : "Jan"
});
produces
{Friend0: "Bob",
Friend1: "Fred",
Friend2: "Gonzo",
FriendFinder0: "Dolly",
FriendFinder1: "Jan"}
Alternatively, without using forEach:
function rekey(obj) {
var rekey = /^(.*?)(\d+)$/;
var nestedobj = {}, newobj = {};
var key, basekeyrv, newkey, oldidx, newidx;
function basekey(key) {
return rekey.exec(key).splice(1);
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
basekeyrv = basekey(key);
newkey = basekeyrv[0];
oldidx = parseInt(basekeyrv[1], 10);
if (!nestedobj[newkey]) {
nestedobj[newkey] = [];
}
nestedobj[newkey].push([oldidx, obj[key]]);
}
}
for (key in nestedobj) {
if (nestedobj.hasOwnProperty(key)) {
nestedobj[key].sort();
for (newidx = 0; newidx < nestedobj[key].length; newidx++) {
newobj[key+newidx] = nestedobj[key][newidx][1];
}
}
}
return newobj;
}
Could you try doing the following:
{
friend: new Array(),
friendFinder: new Array()
}
then you can:
friend.push() - Add to array
var index = friend.indexOf("Bob") - find in array
friend.splice(index, 1) - remove from the array at index the 1 is for the number to remove.

Categories

Resources