0

I have array like this:

a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}]

in javascript. I want to extract all province and put it as in data as mentioned below.

data: [{id: 'province1', text: 'province1'},{id: 'province2', text: 'province2'},
       {id: 'province3', text: 'province3'}]

I tried it with for loop.

for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

But, it's giving me character values..

9
  • you want to go from the first array to the second or... ? Commented May 22, 2014 at 17:20
  • first array to second. I need all provinces separate.. Commented May 22, 2014 at 17:21
  • I need it like, [{id: 'Western', text: 'Western'}...] Commented May 22, 2014 at 17:25
  • 1
    Seems to work here just fine - jsfiddle.net/FkAv7 Commented May 22, 2014 at 17:26
  • I will just quickly add that a faster for-loop defines the iterating variable, and the length, outside (above) the actual loop. Just something to think about. Commented May 22, 2014 at 17:46

2 Answers 2

3

You can build the ids by concatenating a string with a numeric id:

"province" + index // "province1"

Summing up

var data = [];
for (index = 0; index < a.length; ++index) {
    data[index] = { id: 'province' + (index+1), text: a[index].province} ;
}
Sign up to request clarification or add additional context in comments.

Comments

1
var a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}], b = {};

for(var i = a.length; i--; b[a[i].province] = a[i].province);

console.log(b);

Demo

Result is

 {Southern : "Southern ", Central : "Central ", Western: "Western"}

Edit as per the comment:

var a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}];
a = a.map(function(v){
    return { id : v.province, text : v.province };
});

console.log(a);

8 Comments

Why it's giving me object if I am alerting the variable? In console.log it seems ok
@user3609998 You cannot alert an object, try alert(JSON.stringify(b))
we need output in array.. [{Southern : "Southern ", Central : "Central ", Western: "Western"}] (like this)
@user3609998: alert expects a string parameter so your object will be converted to a string, which will be "[Object object]" by default. This is one of the reasons you should use console.log instead of alert for debugging.
actually I need to use variable b like data in this example: jsfiddle.net/pHSdP/2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.