I have an array like this: var arr = ["1:a", "2:b", "3:c"];
From above array I want an object: var obj = { "1": "a", "2": "b", "3": "c" }
I am doing:
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
// I don't know how to make the object
});
Edit:
My Question is mark as duplicate, while the question I asked is totally opposite of the marked duplicate question.
From your code, in place of the comment you could write
obj[valueSplit[0]] = valueSplit[1];
This could be written as a simple reduce:
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
var arr = ["1:a", "2:b", "3:c"];
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
document.write(JSON.stringify(obj));
Just add the assignment.
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
obj[valueSplit[0]] = valueSplit[1];
});
Simply try this
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
map is the object you are looking for.
DEMO
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
document.body.innerHTML += JSON.stringify( map, 0, 4 );
Related
I have following JSON string :
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}
I want location_id as
3,2
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}]
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x].location_id);
console.log(res.join(","));
var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var locationIds = [];
for(var object in json){
locationIds.push(json[object].location_id);
}
console.log(locationIds.join(","));
You can also look into .reduce and create a string manually
var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var location_id_str = d.reduce(function(p, c) {
return p ? p + ',' + c.location_id : c.location_id
},'');
console.log(location_id_str)
try this
var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var output = obj.map( function(item){
return item.location_id;
});
console.log( output.join(",") )
var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var location_array = [];
for( var i = 0; i < arr.length; i++ )
{
location_array.push( arr[i].location_id );
}//for
var location_string = location_array.join(",");
console.log(location_string);
Note: You may need to use JSON.parse() if the arr is in string format initially.
You can use for..of loop
var arr = [{
"name": "Marine Lines",
"location_id": 3
}, {
"name": "Ghatkopar",
"location_id": 2
}];
var res = [];
for ({location_id} of arr) {res.push(location_id)};
console.log(res);
I have an array of strings:
["14: London", "15: Manchester", "16: Bristol"]
I need to change it into an array of objects that would look like this:
[{14: "London"}, {15: "Manchester"}, {16: "Bristol"}]
I assume that the best way to go about this is to first iterate over the array and split each string and then convert it into an object before pushing back into an array.
I can't really figure out how to make it work though, so any help would be much appreciated.
Thanks for your time
Use Array#map method to generate the array.
var arr = ["14: London", "15: Manchester", "16: Bristol"];
// iterate over the array
var res = arr.map(function(v) {
// split the value based on `:`
var splitArr = v.split(':'),
// initialize an object
obj = {};
//define the property value
obj[splitArr[0].trim()] = splitArr[1].trim();
// return the generated object
return obj;
})
console.log(res);
You can map it
var arr = ["14: London", "15: Manchester", "16: Bristol"];
var obj = arr.map(d => {
var split = d.split(": ");
return {
[split[0]] : split[1]
}
});
var arr = ["14: London", "15: Manchester", "16: Bristol"];
var makeObjectFromArray = function(arr) {
if (Object.prototype.toString.call(arr) !== '[object Array]') return arr;
var objects = [];
for (var i = 0, length = arr.length; i < length; i++) {
var obj = arr[i].split(":");
var temp = {};
var key = (typeof obj[1] === 'string') ? obj[0].trim() : obj[0];
var value = (typeof obj[1] === 'string') ? obj[1].trim() : obj[1];
temp[key] = value;
objects.push(temp);
}
return objects;
};
console.log(makeObjectFromArray(arr))
You could also do like this so you can know when your object already has a key/value pair with the same key:
var testArray = ["14: London", "14: London", "15: Manchester", "16: Bristol"];
var testObj = {};
var length = testArray.length;
for ( var i = 0; i < length; i++ ) {
var newTestArray = testArray[i].split(":");
if ( testObj[newTestArray[0]] === undefined ) {
testObj[newTestArray[0]] = newTestArray[1];
} else {
console.log("key: " + newTestArray[0] + " already exists!");
}
}
I have an array of objects like this:
[
{ "key": "fruit", "value": "apple" },
{ "key": "color", "value": "red" },
{ "key": "location", "value": "garden" }
]
I need to convert it to the following format:
[
{ "fruit": "apple" },
{ "color": "red" },
{ "location": "garden" }
]
How can this be done using JavaScript?
You can use .map
var data = [
{"key":"fruit","value":"apple"},
{"key":"color","value":"red"},
{"key":"location","value":"garden"}
];
var result = data.map(function (e) {
var element = {};
element[e.key] = e.value;
return element;
});
console.log(result);
also if you use ES2015 you can do it like this
var result = data.map((e) => {
return {[e.key]: e.value};
});
Example
Using an arrow function, with the data called arr
arr.map(e => {
var o = {};
o[e.key] = e.value;
return o;
});
This generates a new Array and does not modify the original
It can be simplified down to one line as
arr.map(e => ({[e.key]: e.value}));
If you can't assume arrow function support yet, you would write this longhand
arr.map(function (e) {
var o = {};
o[e.key] = e.value;
return o;
});
Using map (as suggested in other answers) or the following will do what you want...
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
var obj = {};
for(var i = 0; i < data.length; i++) {
obj[data[i]["key"]] = data[i]["value"];
}
In Javascript, obj.property and obj['property'] return same things.
obj['property'] is more flexible because the key 'property' could be a string with some space :
obj['pro per ty'] // work
obj.pro per ty // not work
or
var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true
So you could try that.
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];
var data_length = data.length; // just a little optimisation for-loop
for (var i = 0; i < data_length; i++) {
var item = data[i]; // to have a vision close of foreach-loop (foreach item of collection)
new_data[i] = {};
new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]
What you currently have is an array of object, each having two attributes, key and value. If you are not aware of map, you can always run a forEach loop on this array and rearrange the data. Try something like below:
function() {
var newArray = [];
oldArray.forEach(function(x){
var obj= {};
obj[x.key] = x.value;
newArray.push(obj);
});
console.log(newArray);
}
here oldArray is your original data
I want to convert a REST style url into a javascript literal, like this:
from:
var url = "/a/b/c/d";
to:
var obj = {
a:{
b:{
c:{
d:{}
}
}
}
};
How would you do this?
You can probably condense it but here's a solution :
var u = '/a/b/c/d';
var t = u.split('/');
var o = {};
for (var i=t.length; i-->1; ) {
var temp = o;
o = {};
o[t[i]] = temp;
}
The result is o.
My attempt:
var url = '/a/b/c/d';
var fun = function(a) {
var res = {};
res[a[0]] = a.length == 1 ? {} : fun(a.slice(1));
return res;
};
// obj has what you need
var obj = fun(url.split('/').slice(1));
// OTHER EXAMPLE
var t = ['that', 'is', 'so', 'fun'];
console.log(fun(t));
// above returns object: {that: { is: { so: { fun: {} }}}}
How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});