Problem:
Declare a variable named myArray and assign it to an empty array.
Great! Now populate myArray with two strings.
Put your full name in the first string, and your Skype handle in the second.
Next, declare a function named cutName. It should expect a parameter name.
cutName should return an array by breaking up the input string into individual words. For example "Douglas Crockford" should be returned as ["Douglas", "Crockford"]
Declare a new variable named myInfo and assign it to an empty object literal.
Add the following three key-value pairs to myInfo:
Key: fullName
Value: The result of calling cutName on the name string within myArray.
Key: skype
Value: The Skype handle within myArray.
Key: github
Value: If you have a github handle, enter it here as a string. If not, set this to null instead.
My code
var myArray = ['Isaiah Sias', 'isaiahsias15689'];
function cutName(name){
var splitString = name.split(myArray[0]' ');
return splitString;
}
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
Once again I am not sure where I am messing up. I have been working on this problem for a few days now and find myself a little frustrated.
You are very close, you have made a small mistake in the cutName function.
The string.split method takes only 1 parameter, the string to split by. You've tried to pass in the array element as well. Get rid of it! (Keep in mind that the thing we are splitting, name, has been assigned the array element as its value during the function call)
var splitString = name.split(myArray[0]' ');
becomes
var splitString = name.split(' ');
One other issue, you'll need to change your object definition a bit. You have a missing = between myInfo and the start of the object literal. And, when setting property names and values in an object literal you need to use colon instead of equals, so your object
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
becomes
var myInfo = {
fullName: cutName(myArray[0]),
skype: myArray[1],
github: '#kakashihatake'
};
var myArray = ['Isaiah Sias', 'isaiahsias15689'],
github = '#kakashihatake';
function toObject(){
return {
fullName: myArray[0].split(' '),
skype: myArray[1],
github: github
}
}
console.log(toObject());
Related
I am following a tutorial on Youtube about importing data into existing todo list component in React.
If you look at the code below, at the const data object, there are two keys namely lists and listIds. There are two parts which I don't understand.
Why is the key "list-1" a string while the value {id: "list-1",title: "Todo",cards,}
is a normal object? I could not figure out this syntax. If it's JSON format, both key-value should be a in quotation marks.
Is the listIds: ["list-1"] just a normal key-value pair which has an array as its value? If so, why does it has the same name as the one from the initial lists keys? Is this a Destructuring method from ES6?. I just cannot understand the syntax.
const cards = [
{
id: "card-1",
title: "Learning how to cook",
},
{
id: "card-2",
title: "Making sandwich",
},
{
id: "card-3",
title: "Taking the trash out",
},
];
const data = {
lists: {
"list-1": {
id: "list-1",
title: "Todo",
cards,
},
},
listIds: ["list-1"],
};
export default data;
Because "list-1" contains a minus sign and that would be an error for an identifier name. It would be like trying to subtract 1 from "list" and use the expression as a key.
listIds : ["list-1"] is a normal JS key-value expression with a key to the left of : and an array with a single string value to the right.
Object data.lists looks like it contains various sub-objects, each having an ID and listIds is just an array containing all the keys in lists. In your example there is one sub-object and correspondingly, one key in listIds.
One more thing: In a JSON string, keys to the left of : must be in double quotes, however this is a Javascript object, and Javascript objects can have keys without double quotes as long as each key is formatted as a regular Javascript variable, as well as values to the right of : that many times cannot be represented in a JSON string, such as functions for example.
I just thought I'd add a little summary here about declaring key/value pairs in an object declaration. When you declare an object property as in:
let obj = {prop: value};
the left hand side of the property declaration is the property name. There are three possible syntaxes allowed for that:
Plain String - No Quotes
// no quotes - this is allowed when the property name
// doesn't contain any reserved characters
let obj = {prop: value};
Quoted String
// quotes - this is always allowed, but is required when the property name
// does contain reserved characters like a "-" such as your example of "list-1"
let obj = {"prop": value};
Brackets around a variable name
// computed property name. This is used when the property name you want to use
// is in a variable
let someVar = "prop";
let obj = {[someVar]: value};
All three of these options above create the exact same key/value pair in that object.
The right hand side of the prop: value pair can be any Javascript expression like these:
let obj = {prop: 3}; // a number
let obj = {prop: "foo"}; // a string
let obj = {prop: value}; // value from some variable
let obj = {prop: [1,2,3]}; // an array
let obj = {prop: resultFromCallingFunc()}; // the result from calling some function
let obj = {prop: {greeting: "hello"}}; // another object
let obj = {prop: 3 + 4}; // any expression
I am writing a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
function countWords(str) {
var obj = {};
var split = str.split(" ");
return split;
}
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> MUST RETURN {ask: 1, a: 2, bunch: 2, get: 1}
Have any idea?
I wont give you finished code ( thats not the sense of a homework) , but i try to get you to solve the problem on your own.
So far you've already got an array of words.
Next lets declare an object we can assign the properties later.
Then we'll iterate over our array and if the array element doesnt exist in our object as key yet ( if(!obj[array[i]])) well create a new property, with elements name and the value 1.( obj[array[i]=1; )
If the element is a key of that object, lets increase its value.
( obj[array[i]]++;)
Then return the object.
So you could use a javascript Map for this like so:
var myMap = new Map();
myMap.set(keyString, count);
and access the value of the key like so:
myMap.get(keyString);
For more information you can read up here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
I'm calling the .string method on a string and setting that equal to another variable. It returns an array with the [match value, index, and input].
When I try to refer to the second element in the array, it comes back as undefined. Can someone tell me why that is? Heres my code:
var str = "hello world"
var matchArray = str.match("ell");
=>matchArray = ["ell",index:1,input:"hello world"]
var index = matchArray[1];
console.log(index);
=>undefined
Thanks in advance.
var str = "hello world"
var matchArray = str.match("ell");
matchArray is an Array but in javascript as we know we can set properties in array as well as it's an object.
In the above case, matchArray has only the mathces in the array. but the other properties such as index and input are in the object.
If you do console.dir(matchArray) you would get the properties as well.
So to access those properties use object's notation like matchArray.index or matchArray.input
JavaScript is an interesting language. Although the matchArray object is indeed an array, in JS you can add new members to any object. So, matchArray is an array of length 1, but it also has the members index and input defined on it. Try this:
...
console.log(matchArray.index);
console.log(matchArray.input);
We could define a similar object from scratch like this:
var hybridObj = [ "ell" ]; // It's an array
hybridObj.index = 1; // With props
hybridObj.input = "hello world";
my problem is that i have a json-object with and array into here an example.
var object = {
'items':['entry1','entry2']
}
I want to access 'entry2' over a constant string that I receive and shouldn't be changed.
var string = 'items[1]';
The only way I'm solving this problem is over the eval function...
eval('object.'+string);
This returns me entry2.
Is there any other way to achieve this without using eval()?
Like object[string] or object.string
Supposing your string is always the same form, you could extract its parts using a regex :
var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];
Explanation :
The regex builds two groups :
(\w+) : a string
\[(\d+)\] : some digits between brackets
and those groups are at index 1 and 2 of the array returned by match.
+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.
On top of dystroy's anwser, you can use this function:
function getValueFromObject(object, key) {
var m = key.match(/(\w+)\[(\d+)\]/);
return object[m[1]][+m[2]];
}
Example:
var object = {
'items':['entry1','entry2']
}
var string = 'items[1]';
var value = getValueFromObject(object, string); //=> "entry2"
First, you can get the array from inside:
var entries = object.items // entries now is ['entry1','entry2']
Then you need to index that to get the second item (in position 1). So you achieve what you want with:
var answer = entries[1] // answer is now 'entry2'
Of course, you can combine this to get both done in one step:
var answer = object.items[1] // answer is now 'entry2'
... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s
try something like this
object.items[1];
Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:
shopsArray[4].shopName
Edit:
It's working with Pointy's answer but I still have a problem:
shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );
The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.
Can you see what's the problem here?
Edit 2:
More elaborate code:
// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();
// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
shopsArray[i].shopName = $('#secondaryName' + i).val();
shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}
// save new branches to array
for (var j=1; j<=newshopsCounter; j++){
var bName = $('#newName' + j).val();
shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});
alert(bName);
alert(shopArray[1].shopName);
alert(shopsArray[1].shopId);
}
The first and third alerts give the correct values. The second one gives undefined.
You mean something like
shopsArray.push({ shopName: "Fred", value: "Ethel" });
?
edit — now that I know that this is the sort of thing you want to do, I'll clarify.
JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by commas. Thus:
var anObject = { someProperty: "the value" };
creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:
var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;
The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value comes from calling some function:
var fancyObject = { "temperature": getTemperature() };
Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:
shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });
You can even include object literals inside another object literal, as the value of a property:
shopsArray.push({
shopName: "Cheese Shoppe",
shopAddress: {
street1: "207 High Street",
street2: "No. 5",
city: "Austin",
state: "TX"
}
});
You would simply create a hash inside an array to achieve that:
var shopsArray = [
{
shopName: 'value1'
}, {
shopName: 'value2'
}
];
If you have an existing array, use push:
shopsArray.push({ shopName: 'value' });
you can do something like this:
var arr = new Array();
arr['field_name'] = 'field_value';
//to access it on ajax
for (var i in arr){
//field_name is in "i"
//field_value is in arr[i]
}