when ajax data, array:
[ {"id" :"1", "last":"smith", }, {"id" :"2", "last":"doe", }, ]
i trying save array variable more ajax data can added future usage:
var arr = []; arr.push(ajax_data);
however, ajax array added array:
[ [ {"id" :"1", "last":"smith", }, {"id" :"2", "last":"doe", }, ] ]
so here questions:
- what guys suggest there 1 array multiple ajax array addition? in other words, how remove
[]
syntax? - each object have multiple keys. want use "
id
" primary key find object work with. how search , select correct object?
for indexing:
below general array structure having has id
, post_id
2 keys, can have other keys (values copied , pasted demonstration). number of objects can 100.
this ajax data , concat
array.
as @jfriend00 pointed out, indexing id can inefficient. way of indexing large array id?
what guys suggest there 1 array multiple ajax array addition? in other words, how remove [] syntax?
you need use 1 of methods adds multiple elements array rather adds array (see options below).
to add onto existing array, can use .push()
or .splice()
. can use .concat()
, returns new array have assign prior variable:
var arr = []; var newdata = [ {"id" :"1", "last":"smith", }, {"id" :"2", "last":"doe", }, ]; // add newdata onto arr using .push() arr.push.apply(arr, newdata); // add newdata onto arr using .concat() // remember .concat() returns new array arr = arr.concat(newdata);
using .splice()
bit more involved , if trying replace elements.
// put first 2 `.splice()` arguments onto front of array newdata.unshift(arr.length, 0); arr.splice.apply(arr, newdata);
each object have multiple keys. want use "id" primary key find object work with. how search , select correct object?
if want able index id, array not efficient structure. have search every object in array find matching id. either create separate index id or change way store data. how change how store data depends upon how need access it, whether there multiple objects same keys, whether objects have more 1 key, etc... you'd have specify lot more detail on needs make recommendation.
for 100 entries, can brute force search:
function findbyid(array, id) { (var = 0; < array.length; i++) { if (array[i].id === id) { return array[i]; } } return null; }
if want index them , ids unique , order not relevant, instead of array, store in object:
var data = {}; // add new data our storage newdata.foreach(function(item) { data[item.id] = item; });
then, access id:
var item = data[id];
in es6 (or via transpiling or polyfill), can use map
object.
var data = new map(); // add new data our storage newdata.foreach(function(item) { data.set(item.id, item); });
then, access id:
var item = data.get(id);
an advantage of map
object on using regular js object id can data type (including object). when using plain js object, has coerced unique string.