I'm looking for a native JavaScript method to merge 2 arrays into a literal object.
Turn this:
var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"];
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];
Into this:
{
"obj" : {
"blue" : "james",
"yellow" : "john",
"red" : "robert",
"green" : "michael",
"brown" : "william",
"gray" : "david",
"grey" : "richard",
"orange" : "wayne"
}
}
You can do this with a fairly simple loop:
var result = {obj: {}};
for (var i=0; i<x.length; i++) {
result.obj[x[i]] = y[i];
}
This assumes that x and y are always the same length. If they're not, you just need to add a bit more code for checking the lengths.
var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"];
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];
function merge2array(a, b) {
var obj = {};
var l = a.length;
var i;
for (i = 0; i < l; i++) {
obj[a[i]] = b[i];
}
return obj;
}
var obj = merge2array(x, y);
console.log(obj);
This will return this object:
{
"blue" : "james",
"yellow" : "john",
"red" : "robert",
"green" : "michael",
"brown" : "william",
"gray" : "david",
"grey" : "richard",
"orange" : "wayne"
}
Then you can build your desired object:
var r = { obj: obj };
console.log(r);
There isn't a native method.
Here you can find two ways of achieving it
The first method, m1, will validate the length of your arrays, if it doesn't match it will throw an exception.
function m1(keys, values)
{
// in case the arrays have different sizes
if (keys.length != values.length)
throw new Error("Arrays are not of the same size");
var result = {};
for (var i in keys)
{
result[keys[i]] = values[i];
}
return result;
}
The second method, m2, will allow you to have more keys than values, and fill the missing values with null.
function m2(keys, values)
{
// alternative handling for different sizes
if (keys.length < values.length)
throw new Error("You can't have more values than keys");
var result = {};
for (var i in keys)
{
var val = null;
if (i < values.length)
val = values[i];
result[keys[i]] = val;
}
return result;
}
Both methods return an object, to have an object exactly as you described you will can do this:
var x = {};
x.obj = m1([1, 2, 3], ["a", "b", "c"]);
For a compact version (without validations) you can use:
function m(k,v){r={};for (i in k)r[k[i]]=v[i];return r}
Usage:
var x = { obj: m([1,2],["A","B"]) };
Change m to the desired function name.
Reference
Javascript objects
Javascript arrays
Javascript for/in loop
Javascript errors
Javascript Error object
fastest(using while--,caching length) / shortest way?
var a=['blue','yellow','red','green','brown','grey','gray','orange'],
b=['james','john','robert','michael','william','david','richard','wayne'],
c=[],d=a.length;while(d--)c[a[d]]=b[d];
var x={obj:c};
also as function (c&d are placeholder so you don't need to write var and save bytes)
the name of the function can be placed infront or after 'function'...whatever
function(a,b,c,d){c=[],d=a.length;while(d--)c[a[d]]=b[d];return c}
Related
I want to output as a string from this code. I just checked its length but I could not output as a string again like-('joy', 'james';). I don't know where is my problem with the output string. please help to solve this problem. thank you.
function oddFriend(name) {
let oddFr = [];
for (let i = 0; i < name.length; i++) {
let frName = name[i].length;
console.log(frName);
if (frName % 2 != 0) {
oddFr.push(frName);
}
}
return oddFr;
}
console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));
In the oddFriend function, you are pushing the length of the name to the array instead of the name itself. Trying pushing name[i] instead.
You just need to check that the length of the name isn't an even number, and then push the element into the output array, not the length of the element.
function oddFriend(list) {
let oddFr = [];
for (let i = 0; i < list.length; i++) {
const len = list[i].length;
if (len % 2 !== 0) {
oddFr.push(list[i]);
}
}
return oddFr;
}
console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));
You could also use filter for this.
function oddFriend(list) {
return list.filter(name => {
return name.length % 2 !== 0;
});
}
console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));
Your result is the number of chars (length of string) which is frName but you need each result to be the actual string which is name[i].
Corrected OP code
function oddFriend(name) {
let oddFr = [];
for (let i = 0; i < name.length; i++) {
let frName = name[i].length;
if (frName % 2 === 1) {
oddFr.push(name[i]);
}
}
return oddFr;
}
console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));
Fast and terse alternative
const array = ["jon", "james", "robert", "george", "Leo", "joy"];
let odd = array.flatMap(o => o.length % 2 === 1 ? [o] : []);
console.log(odd);
You properly use that name length to check if the length is odd using the modulus operator, but you should push the original name parameter passed into the function instead of that value which is set to the name length.
function filterOddLengths(stringsToFilter) {
let oddLengths = [];
for (let i = 0; i < stringsToFilter.length; i++) {
if (stringsToFilter[i].length % 2 !== 0) {
oddLengths.push(stringsToFilter[i]);
}
}
return oddLengths;
}
console.log(filterOddLengths(["jon", "james", "robert", "george", "Leo", "joy"]));
Update: Please use more specific variable names. The parameter named name is very confusing because the function expects an array of names.
I have an JSON object (hope so?):
[{"label":"label1","value":"value1"}
{"label":"label2","value":"value2"}
{"label":"label3","value":"value3"}]
I want to convert/extract that in 2 arrays like:
var labels = [label1,label2,label3]
var values = [value1,value2,value3]
I have no idea...
Assuming you would like two arrays and there is only ever two properties called label and value in each object, then this would be fine: -
var json_string = '[{"label":"label1", "value":"value1"}, {"label":"label2", "value":"value2"}, {"label":"label3", "value":"value3"}]';
var array = JSON.parse(json_string);
var labels = [];
var values = [];
for (var i = 0; i < array.length; i++) {
labels.push(array[i].label);
values.push(array[i].value);
}
Output: -
console.log(labels); // ["label1", "label2", "label3"]
console.log(values); // ["value1", "value2", "value3"]
You could use the map function to create your results:
var dataObj = [{"label":"label1","value":"value1"},
{"label":"label2","value":"value2"},
{"label":"label3","value":"value3"}];
var labels = dataObj.map(function(obj) {return obj.label;});
var values = dataObj.map(function(obj) {return obj.value;});
I think this solution is more elegant then manually iterating the array.
One other implementation could be;
var dataObj = [{"label":"label1","value":"value1"},
{"label":"label2","value":"value2"},
{"label":"label3","value":"value3"}],
dataStr = JSON.stringify(dataObj),
r = /label":"(\w+).+?value":"(\w+)/g,
m = [],
values = [],
labels = [];
while ((m = r.exec(dataStr)) !== null){
labels.push(m[1]);
values.push(m[2]);
}
console.log(labels, values); // [ 'label1', 'label2', 'label3' ] [ 'value1', 'value2', 'value3' ]
A proposal with one object as result with dynamic keys.
var array = [{ "label": "label1", "value": "value1" }, { "label": "label2", "value": "value2" }, { "label": "label3", "value": "value3" }],
result = {};
array.forEach(function (a) {
['label', 'value'].forEach(function (k) {
result[k] = result[k] || [];
result[k].push(a[k]);
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Is it possible to create complex objects at runtime in javascript ? If so, what is the correct syntax ?
var food = {};
food["fruit"]["yellow"] = "banana";
food["meat"]["red"] = "steak";
food."fruit"."green" = "apple";
It's not clear what you're trying to do. If you want to build that object up all at once, then you could do something like:
var food = {
fruit: {
yellow: 'banana',
green: 'apple'
},
meat: {
red: 'steak'
}
};
If you need to piece it together one nested object at a time, then you just need to make sure that you are creating a new object to add properties to.
For example, your line:
food["fruit"]["yellow"] = "banana";
will probably fail because food.fruit does not exist.
You should do:
var food = {};
food.fruit = {};
food.fruit.yellow = 'banana';
You could write a function to add data to your object.
e.g.
function addEntry(obj, entry) {
if(entry.length < 2) return;
if(entry.length === 2) obj[entry[0]] = entry[1];
else {
if(!obj[entry[0]] || typeof obj[entry[0]] !== "object") obj[entry[0]] = {};
addEntry(obj[entry[0]], entry.slice(1));
}
}
var data = [
["fruit", "yellow", "banana"],
["meat", "red", "steak"],
["fruit", "green", "apple"]
];
var obj = {};
for(var i = 0; i < data.length; i++) {
addEntry(obj, data[i]);
}
console.log(obj);
I'm new to JavaScript and im confused how to extract a particular key value from a JSON file:
var me = {"fcolors": ["blue", "green", "whitesmoke"],"fire": ["pink", "grey", "red"]};
i want only fcolour values
fcolour = [];
for (var key in me) {
if (me[key] instanceof Array) {
for (var i = 0; i < me[key].length; i++) {
console.log();
fcolour.push(me[key][i])
}
}
}
i want result to be fcolour=["blue", "green", "whitesmoke"]
thanks in advance and any comment is appreciated.....
You dont need to loop to get its value since your json doesnt have array of fcolors:
me.fcolors will give you ["blue", "green", "whitesmoke"]
Plunker Here
For Multiple objects:
var data = [{
"fcolors": ["blue", "green", "whitesmoke"],
"fire": ["pink", "grey", "red"]
}, {
"fcolors": ["red", "white", "yellow"],
"fire": ["black", "gray", "pink"]
}];
var fcolors = [];
for (var i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty('fcolors')) {
fcolors.push(data[i].fcolors);
}
}
console.log(fcolors);
fcolors contains array
Plunker
Why are you looping JSON , when you can easily access given JSON as
me.fcolors; // It will give you ["blue", "green", "whitesmoke"]
If your array is a flat object, using the following will get the wanted value.
var jsonData = {fcolors: [...], fire: [...]};
if (jsonData.hasOwnProperty('fcolors')) {
var fcolors = jsonData.fcolors;
}
If you have multiple similar objects in the array, you could use the following to grab all the values.
var jsonData = [
{fcolors: [...], fire: [...]},
{fcolors: [...], fire: [...]},
{fcolors: [...], fire: [...]}
];
var fcolors = [];
for (var i = 0; i < jsonData.length; i++) {
var current = jsonData[i];
if (current.hasOwnProperty('fcolors')) {
fcolors.push(current.fcolors);
}
}
After which fcolors is a multidimensional array.
I have the following array
var a = ["Banana/hgd/kjjkds", "Orange/kldj/kdl",
"Apple/jlds/ldks", "Mango/dsfj/dskj"]
Now I want to re-create it as below and make the output
{
"a1" : "Banana",
"a2" : "hgd",
"a3" : "kjjkds"
}
{
"a1" : "Orange",
"a2" : "kldj",
"a3" : "kdl"
}
{
"a1" : "Apple",
"a2" : "jlds",
"a3" : "ldks"
}
{
"a1" : "Mango",
"a2" : "dsfj",
"a3" : "dskj"
}
I tried the following method but without any success:
var b = [];
for (var i = 0; i< a.length; i++) {
b['a1'] = a[i].split("/")[0];
b['a2'] = a[i].split("/")[1];
b['a3'] = a[i].split("/")[2];
console.log(b);
b.push(b);
}
The console prints all the array created but the array b only shows the last one. How can i get it to work? Please help.
try this:
var spl, b = [];
for (var i = 0, len = a.length; i < len; i++) {
spl = a[i].split("/"); /* execute split() just once */
b[i] = {
'a1': spl[0],
'a2': spl[1],
'a3': spl[2]
}
}
console.log(b);
You are pushing the array onto itself. That should set off warning signals.
Instead, you need an output array, and a temporary array to add the keys to.
var b = [], t, s, l = a.length, i;
for( i=0; i<l; i++) {
s = a[i].split("/");
t = {
"a1":s[0],
"a2":s[1],
"a3":s[2]
}
b.push(t);
}
I've also added a couple of optimisations in there.