0

I have an array as below:

[{
    "category_type": 1,
    "category": 2,
    "name": "gut",
    "description": "bg",
    "registered_location": "1234 1234",
    "current_location": null,
    "contact_person": 4046,
    "barcode": "25757767",
    "nfc_tag_id": "44444543",
    "unit_of_measure": "crate",
    "date_added": "2014-11-13",
    "status": 1
}]

I am able to loop through it and get all the values like this:

$.each(data, function(key, object){
    $.each(object, function(key, value){
        console.log(value);
    })
})

I have a certain number of spans that I'd like to get their texts from the different values.The spans are like:

<p>Category Type: <span></span></p>
<p>Category: <span></span></p>
<p>Name: <span></span></p>
<p>Description: <span></span></p>
<p>Registered Location: <span></span></p>
<p>Current Location: <span></span></p>
<p>Contact Person: <span></span></p>
<p>Barcode: <span></span></p>
<p>NFC Tag ID: <span></span></p>
<p>Unit of measure: <span></span></p>
<p>Date Added: <span></span></p>
<p>Status: <span></span></p>

I want all the empty spans above to get their texts from the JSON values I get above. How can I achieve this?

5
  • 2
    It's unclear what you want to do with the values. Could you add some example output you're looking for? Commented Nov 13, 2014 at 9:40
  • var span = $('<span />').html(value); $( "body" ).append( span ); Commented Nov 13, 2014 at 9:43
  • I just edited my post Commented Nov 13, 2014 at 9:44
  • @Denny just posted an answer Commented Nov 13, 2014 at 10:25
  • @Denny The data your are showing is not real JSON. JSON would be alphabetical ordered. Commented Nov 13, 2014 at 10:40

9 Answers 9

1

The usual way to achieve what you want is to tag each paragraph with a class or id, e.g.

<p id="category_type">Category Type: <span></span></p>
<p id="category">Category: <span></span></p>
<p id="name">Name: <span></span></p>
...

Then, let's say data is your original array, and obj = data[0] contains the key/value pairs you want to use. You can then do something like

$.each(obj, function(key, value) {
    // $('#category_type') selects the element with id "category_type", etc.
    $('#' + key).find('span').text(value);
});

Now, this requires you to be able to control the original HTML (e.g. if you are generating it from a template on the server). If you do not have control over the HTML, you will have to do something a bit more hacky, where you parse the contents of the paragraph to determine which data value corresponds to it. For example,

$('p').each(function() {
    var txt = $(this).text(); // `this` is the paragraph element
    var key = txt.trim().toLowerCase().replace(':', '').replace(' ', '_');
    // if `txt` is "Category Type: ", then `key` should be "category_type", etc.
    $(this).find('span').text(obj[key]);
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can wrap your p tags in some div and then use .eq() like

 var counter = 0;
 $.each(object, function(key, value){
    $('.container p').eq(counter).children('span').html(value);
    counter++;
 })

UPD As GuyT noticed, the order can change, so you can try smth like

 $.each(object, function(key, value){
    var str = key.split("_").map(function(elm){
       return elm.charAt(0).toUpperCase() + elm.slice(1);
    }).join(" ");
    $('.container p:contains("'+str+'")').children('span').html(value);
 })

Fiddle displays how to select needed p tags.

10 Comments

Same question: what if the order changes?
@Y.Puzyrenko And if it is multilanguage?
@GuyT So what's the problem?
@Y.Puzyrenko You are searching on e.g.: 'Category Type'. In Dutch this will be 'Categorie' so your logic isn't right anymore(because the record/model will not change).
@GuyT So you need either couple of jsons or some sort of dictionary.
|
0

Loop throught all the p, and do the following on it: get the text of it, replace <span></span> and trim it, so just get the text from it like: Category Type:.

With this, replace the : character, convert it to lowercase, and replace the spaces to _ character.

Then you will have the key, like: category_type, and then you can use that on your JSON.

Get the array value, and put it in the $(this).find('span');

1 Comment

What if the application is multilanguage?
0

Introducing Handlebars and JavaScript templating!

First we create a template

var products = {'products': [yourDataArray] };
var template = "{{#each products}}" + //each iteration will loop over a product
               "<span>{{category_type}}</span>" + //just keep on adding spans to this template.
               "{{/each}}";

var compiledTemplate = Handlebars.compile(template);
var htmlFromTemplate = compiledTemplate(yourData);

Now just append the htmlFromTemplate to your container.

$('.myContainer').append(htmlFromTemplate);

This is completely untested, but should work, or at least provide a hint in the right direction.

Comments

0

From what I understand, you have an array of JSON objects. And your trying to loop through the array and access the objects values using their attributes. If so this would be the implementation:

// ARRAY OF JSON OBJECTS
var data = [{"Name":"foo"},{"Name":"bar"}];    

// YOUR LOOP
$.each(data, function(key, value){
    $('#target').append("<p>Name:<span>" + value.Name + "</span></p>");
    // AND SO ON...
});

This will Result in something like this:

<p>Name:<span>foo</span></p>
<p>Name:<span>bar</span></p>

This should do it. I hope this was what you were looking for.

Comments

0
var obj = array[0], index = 0;

// Also you can use jQuery each function
for(var key in obj){
    if(obj.hasOwnProperty(key)){
        var value = obj[key];
        $('p').eq(index++).find('span').text(value);
    }
}

var array = [{
    "category_type": 1,
    "category": 2,
    "name": "gut",
    "description": "bg",
    "registered_location": "1234 1234",
    "current_location": null,
    "contact_person": 4046,
    "barcode": "25757767",
    "nfc_tag_id": "44444543",
    "unit_of_measure": "crate",
    "date_added": "2014-11-13",
    "status": 1
}], obj = array[0], index = 0;

// Also you can use jQuery each function
for(var key in obj){
    if(obj.hasOwnProperty(key)){
        var value = obj[key];
        $('p').eq(index++).find('span').text(value);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Category Type: <span></span></p>
<p>Category: <span></span></p>
<p>Name: <span></span></p>
<p>Description: <span></span></p>
<p>Registered Location: <span></span></p>
<p>Current Location: <span></span></p>
<p>Contact Person: <span></span></p>
<p>Barcode: <span></span></p>
<p>NFC Tag ID: <span></span></p>
<p>Unit of measure: <span></span></p>
<p>Date Added: <span></span></p>
<p>Status: <span></span></p>

4 Comments

And what if the object comes back in an other order?
That is what i just wanted to ask! agreed with GuyT.
@Jai This is also what I'm asking myself! I've no idea :)
@Jai use a @ so people get notified :). ABCFORCE, I've created a fiddle for you: jsfiddle.net/3kx5bvg5/2 (I've changed the first 2 properties, see the result ;))
0

A possible approach would be to use $.each. First you loop through the object and save the values in a temporary array. Afterwards you do an $.each on every <span>.

var obj = {
    "category_type": 1,
    "category": 2,
    "name": "gut",
    "description": "bg",
    "registered_location": "1234 1234",
    "current_location": null,
    "contact_person": 4046,
    "barcode": "25757767",
    "nfc_tag_id": "44444543",
    "unit_of_measure": "crate",
    "date_added": "2014-11-13",
    "status": 1 
};

var temp = []; 

$.each(obj, function(key, value){
    temp.push(value); 
});

$.each($('span'), function( index ){
    $( this ).html(temp[index]); 
});

See the fiddle.


A better solution would be to use ids. Give your Category Type span an id of category_type and map the values. Look up for the id and take it's value.

HTML <p>Category Type: <span id="category_type"></span></p> and so on

$.each(obj, function(key, value){
    $( '#' + key).html(value);
});

This approach is much better because if the values would come back in an other order they still will be placed in the right span.

Check the fiddle.

Comments

0

You can go throuch all span elements like this:

$('span').each(function() {
    //some code to insert data into span
});

Or you might add ids to each span which are same as index name and add values to it.

var index, value;
for(index in data) {
    value = data[index];
    $('#' + index).html(value);
}

Comments

0

Try this:

var txt = '';
$.each(data, function (key, object) {
    $.each(object, function (key, value) {
        if (key.indexOf('_') !== -1) {
            var c1 = key.split('_')[0].toString().charAt(0).toUpperCase() + key.split('_')[0].toString().slice(1);
            var d1 = key.split('_')[1].toString().charAt(0).toUpperCase() + key.split('_')[1].toString().slice(1);
            txt = c1 + ' ' + d1;
            console.log(txt);
            $('p:contains(' + txt + ':)').find('span').text(value);
        } else {
            txt = key.charAt(0).toUpperCase() + key.slice(1);
            $('p:contains(' + txt + ':)').find('span').text(value);
        }
    });
});

checkout the demo below:

Demo @ Fiddle

2 Comments

Category Type is wrong hehe and what if the application is multi-language? ;)
Then there will be more intelligent way of doing that, although about your comment hehe its done you can see in the updated fiddle though.

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.