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);
Related
You have a string that is in a following format: "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach" and etc.
In Javascript (use .split()), write code to parse a string like this(can be 100000 characters long) that puts the input in 2 different arrays(array key, array values) such that the arrays would llok like the following:
key = ["Applejack", "Lemon+Vodka"]
values = ["A.J+Applecar","AlfieCocktail+Sunset+SexOnTheBeach"]
key = string.split(',').map(x=>x.split("=")[0])
values = string.split(',').map(x=>x.split("=")[1])
You could do something like this
var str = "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
var first = str.split(',');
var keys = [];
var values = [];
for(let i = 0; i < first.length; i++){
let in_two = first[i].split('=');
keys.push(in_two[0]);
values.push(in_two[1]);
}
console.log(keys);
console.log(values);
You can do it like this:
let str = "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
let allValues = str.split(','), keys = [], values = [];
allValues.forEach(value => {
const [k,v] = value.split('=');
keys.push(k);
values.push(v);
})
console.log(keys,values);
You can simply use map with reduce.
const str =
"Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
const [keys, values] = str
.split(",")
.map((item) => item.split("="))
.reduce(
(acc, item) => [acc[0].concat(item[0]), acc[1].concat(item[1])],
[[], []]
);
console.log(keys, values);
I have a string:
var string = "test,test2";
That I turn into an array:
var array = string.split(",");
Then I wrap that array into a larger array:
var paragraphs = [array];
Which outputs:
[['test','test2']]
But I need it to output:
[['test'],['test2']]
Any clue how I can do this?
Just map each item into an array containing that item:
var string = "test,test2";
var result = string.split(",").map(x => [x]);
// ^--------------
console.log(result);
let test_string = "test,test2";
let result = test_string.split(',').map(item => [item])
console.log(result)
You can get expected result using array Concatenation.
var string = "test,test2";
var array = string.split(",");
var finalArray=[[array[0]]].concat([[array[1]]])
console.log(JSON.stringify(finalArray));
What version of JavaScript are you targeting?
This might be a general answer:
var arr = "test,test2".split(",");
var i = arr.length;
while(i--)
arr[i] = [arr[i]];
I want to convert the below array:
["A:100","B:234","C:124","D:634","E:543","F:657"];
Into:
["100:234:124:634:543:657"];
How to do this?
So not sure why you would want that particular output since it would just be a single item in an array but this should work:
var testArray = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var resultArray = [];
for(var i = 0; i < testArray.length; ++i) {
resultArray.push(testArray[i].split(':')[1]);
}
var strValue = resultArray.join(':');
console.log(strValue);
resultArray = [strValue];
console.log(resultArray);
You could iterate the array, return the number on the right and join it with ':'.
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(function (a) {
return a.match(/\d*$/);
}).join(':')];
console.log(result);
Or a bit shorter
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(RegExp.prototype.exec.bind(/\d*$/)).join(':')];
console.log(result);
<script>
var arr=["A:100","B:234","C:124","D:634","E:543","F:657"];
var str='';
for(var i=0;i<arr.length;i++){
str+=arr[i].split(":")[1]+":";
}
console.log(str.substring(0, str.length - 1));
</script>
You could just keep the number behind ":" and join new elements with ":"
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var results = [data.map(x => x.split(":")[1]).join(":")];
console.log(results);
You join it with what you want :, split it by what you don't won't /\D\:/ (non digit followed by :), and then join it using an empty string '':
var arr = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var result = [arr.join(':').split(/\D\:/).join('')];
console.log(result);
let the array be
var array=
[
"me=Salman","Profession=student","class=highschool"
]
How do I extract the value of 'me' here?
Try this:
var result = '';
for(var values in array){
if(values.indexOf('me=') !== -1 ){
result = values.split('=')[1];
break;
}
}
You will need to search the array for your desired portion of the string, then remove what you searched for from the indicated string.
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var findMatch = "me=";
var foundString = "Did not find a match for '"+findMatch+"'.";
var i = 0;
for (i = 0; i<array.length; i++) //search the array
{
if(array[i].indexOf(findMatch) != -1) // if a match is found
{
foundString = array[i]; //set current index to foundString
foundString = foundString.substring(findMatch.length, array[i].length); //remove 'me=' from found string
}
}
Try this:
var a = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var result = a.filter(function(e){return /me=/.test(e);})[0]; // Find element in array
result = result.length ? result.split('=').pop() : null; // Get value
Or function:
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
function getVal(arr, key){
var reg = new RegExp(key + '=');
var result = arr.filter(function(e){ return reg.test(e)})[0];
return result.length ? result.split('=').pop() : null;
}
console.log( getMe(array, 'me') );
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;
});