0

I think I'm missing an obvious answer. I have an array of arrays, like this

var arraylist = [
    {
    "id" = 0,
    "title" = "title number 1",
    "info" = "some info etc 1"
    },
    {
    "id" = 1,
    "title" = "title number 2",
    "info" = "some info etc 2"
    },
]

...etc. And a function that makes some html from each array, which is appended to a ul element.

function makeBox(){
    for (i = 0; i < arraylist.length; i++ ) {
        var boxHTML = '<li id="' + arraylist[i].id + '">'
            + '<div>' + arraylist[i].title + '</div>'
            + '</li>'
        $('ul').append(boxHTML);
    };
};

Now using a click function, on clicking the 'li' I want the relevant array from arraylist to be copied to a new array.

newArrayList = []

So clicking on li #0 would copy the first array from 'arraylist' to the 'newArrayList'.

I will then be making different HTML from 'newArrayList' using different values. So in the makeBox function I won't show the value "info", but when I make HTML from newArrayList I will. I could use innerHTML to get the data back out of the HTML to the newArrayList, but would have to append "info" to a hidden span, or something. This seems like the long way round. So what's the easy way?

I'm just learning so go easy on me. Also did a good search and couldn't find the answer. If it's already there please direct me politely.

1
  • The arraylist declaration has syntax errors. Instead of the equals signs, you should use colons. Commented Nov 7, 2015 at 22:13

2 Answers 2

3

So a few notes:

  • It's not an array of arrays. It's an array of objects. The [ ] block is an array. The { } is an object.
  • The $('ul') will select ALL uls on the page, not necessarily just the one you intend.
  • The object structure is incorrect, it should be using colon (:) rather than equal (=) characters. It should look more like this:

    var arraylist = [{
        "id": 0,
        "title": "title number 1",
        "info": "some info etc 1"
    }, {
        "id": 1,
        "title": "title number 2",
        "info": "some info etc 2"
    }]
    

Here is a modified version of your function.

function makeBox(){
  var $ul = $('ul.from_array_one');
  for (var i = 0; i < arraylist.length; i++) {
    var item = arraylist[i];
    var $boxHTML = $('<li id="' + item.id + '">' + item.title + '</li>');
    $boxHTML.click(onSelectItem(item));
    $ul.append($boxHTML);
  };
};

Where a new function exists accepting the array object item, such as:

function onSelectItem( item ){
  return function(){
    var $ul2 = $('ul.from_array_two');
    var $boxHTML2 = $('<li id="' + item.id + '">' + item.info + '</li>');
    $ul2.append($boxHTML2);
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Good answer. The selectItem function could be as follows: function selectItem(item) { $('span').html("info = "+item.info); } -- This will show the info in all spans on the page.
Hey Shaun, I really like this answer. Easy to understand for me. I've been messing with it here in jsfiddle, but it always appends the same object. Am I missing something in the click function?
Hi @nathan - I've updated the code a little as it was my mistake. Because the click event doesn't fire until long after the array has been looped around, the item is showing as the last item in the array. By passing a closure from another function it makes sure the value is set at the time of iteration.
Please excuse my editing; for some unknown reason a code-block following a list-element needs to be indented twice to look like a code block; unfortunately it then also looks like it belongs to the preceding list-item. Which is weird, I know. Also I added some in-line code samples (using the backtick (`) characters to surround the code-string).
Thanks again. Here is the updated jsfiddle. This is really nice and working perfectly. Hugely appreciated.
1

Shaun's solution should work when implemented correctly (one point for your effort).

Here is another way.

I modified your (OP's) function so can be reused for other array of same types. Since you're learning, I encourage you to read up on DRY principle a.k.a. "don't repeat yourself". Adhering to this principle while designing your code, will help you write code that is more reusable resulting in shorter code, in the longer run a more maintainable code base. And in the process you will become an even better coder.

var arraylist = [
    {
    "id": 0,
    "title": "title number 1",
    "info": "some info etc 1"
    },
    {
    "id" : 1,
    "title": "title number 2",
    "info": "some info etc 2"
    },
];
var newArrayList = [];

///
function makeBox(arrayToMake, ulToAppendTo, liClass){
    for (i = 0; i < arrayToMake.length; i++ ) {
        var boxHTML = '<li class="'+liClass+'" id="' + arrayToMake[i].id + '">'
            + '<div>' + arrayToMake[i].title + '</div>'
            + '</li>'
        $(ulToAppendTo).append(boxHTML);
    };
};

var firstListClass = "first_list_item";
var secondListClass = "second_list_item";

makeBox(arraylist,'.ul_one',firstListClass);
$("."+firstListClass).click(function(){
	copyArray(arraylist,newArrayList);    
   	makeBox(newArrayList,'.ul_two',secondListClass);
});

function copyArray(sourceArray, targetArray)
{
   sourceArray.forEach(function(item){
       //for demo purpose only
       item.title="new title " + item.id;
       targetArray.push(item);
   });}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>first array result</p>
<ul class='ul_one'></ul>
<p>new array result</p>
<ul class='ul_two'></ul>

1 Comment

Thanks for this and the other tips. It took me a while to get my head around it, but I think i've got it. having a go at implementing it now.

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.