How to dynamically create a ARRAY based on a AJAX response? - javascript

How do I dynamically create a array after getting a AJAX response ?
The variable data.villages is my response.
I loop over its value using the jQuery each function:
$.each(data.villages, function(key, value) {
//Here I have the 2 variables: value.id and value.name
//Now I need to build a array where the value.id is the KEY and the content is name : value.name
//After I need to create an array with all the arrays
});
My final array should look like this:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
I need this to get the name value (or any other property) by knowing the ID....
Can you also show me example on how to get this data by knowing the ID ?

To create an array of objects from your json response you should be able to do something like this:
var arrayOfObjects = [];
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
arrayOfObjects.push(data.villages[i]);
}
What I think you actually want is an object. You can object like so:
var objectFromJson= {};
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
var currentItem = data.villages[i];
objectFromJson[currentItem.WhatEverPropertyYouWantForTheKey] = currentItem;
}

I think your final array is wrong:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
must be:
[
{ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] }
]
that is, an array with an object with the id=234141 and value [{name: ....}]
You can achieve that with:
data.villages = "your returned data array";
var newArray = [ { 234141: [] } ];
$.each(data.villages, function(key, value) {
newArray[0]['234141'].push({key: value};
}

you could try something like
arr = new Array();
arr[value.key] = {var1: 'vila1', var2: 'vila2'};
you are just storing json

Related

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

How to safely wrap an object into an array in JavaScript

I have a function that takes in an Array, iterates over it finding all Objects and displays them to the UI.
In rare cases, I have to supply an Object (result from a WS as application/JSON) which is not an Array by default and hence my function fails to iterate over it and display on the UI.
In normal cases my Array looks like this:
[
{ "name" : "foo"},
{ "name" : "bar"},
{ "name" : "baz"}
]
and this works like it is supposed to. However, sometimes the data I get could be this:
{ "name" : "I am not in a List"}
and my function that takes in an array looks like this:
function loadJSONIntoUI(data) {
for (var aMsg = 0; aMsg < data.length(); aMsg++) {
// Do something with each `index` in the List
}
}
Is there a way I can detect that the single object which is not an array is an odd one and probably put it into a List on the fly and pass it to a function?
So far I have tried to use typeof and also tried to create a new Array on the fly and push my object into it but it prints out a 1 when I do that.
A one liner using Array.prototype.flat:
[couldBeArray].flat()
Examples:
const anObj = {name: "Hi"};
const anArr = [{name: "Hi"}];
const wrapped1 = [anObj].flat()
const wrapped2 = [anArr].flat()
console.log(wrapped1); // wrapped1 is [{name: "Hi"}]
console.log(wrapped2); // wrapped2 is [{name: "Hi"}]
You can simply use Array.concat() to auto-wrap an object into an array:
const obj = {name: "foo"};
const arr = [{name: "bar"}];
const result1 = [].concat(obj); // result1 is [{name: "foo"}]
const result2 = [].concat(arr); // result2 is [{name: "bar"}]
console.log(result1)
console.log(result2)
you can transform it in an array if is not and let iterate one time:
function loadJSONIntoUI(data) {
if(!(data instanceof Array)){
data = [data];
}
for (var aMsg = 0; aMsg < data.length; aMsg++) {
// Do something with each `index` in the List
}
}
Also, length doesn't need to be called like a method.
Let me know if it works
Cheers
Array.isArray can be used to achieve what you need:
function loadJSONIntoUI(data) {
if(!Array.isArray(data)) {
data = [data];
}
for (var aMsg = 0; aMsg < data.length(); aMsg++) {
// Do something with each `index` in the List
}
}
You need to check for an array and fix an error - should be just data.length, no brackets. See code below, check demo - https://fiddle.jshell.net/ermakovnikolay/fgedaubm/
function loadJSONIntoUI(data) {
var data = Array.isArray(data) ? data : [ data ];
for (var aMsg = 0; aMsg < data.length; aMsg++) {
// Do something with each `index` in the List
console.log(data[aMsg]);
}
}
You can use Array.of(). So in your case Array.of(data) returns [{ "name" : "I am not in a List"}]

Converting array in to custom format

How can I convert the below array in to another format as specified below:
My array:
var test=[{"1":"Input"},{"2":"Output"}]
Converted array:
var result=
[
{
"id": "1",
"name": "Input"
},
{
"id": "2",
" name": "Output"
}
]
I tried with this code but not working.
var result = [];
for (var i = 0; i < test.length; i++) {
var newArray = {
id: Object.keys(test[i])[i],
name: test[i].name
}
result.push(newArray);
}
Inner array object doesn't have name property, so test[i].name will be undefined. You need to get the value using the key value. Also you can simplify your code using map() instead of for loop.
var test = [{
"1": "Input"
}, {
"2": "Output"
}];
var res = test.map(function(v) { // iterating over array object
var k = Object.keys(v)[0]; // getting object keys as an array & retrieving first key
return {
id: k, // setting id property as key
name: v[k] // and name property as value
}
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
You should use array.prototype.map for converting an array to another array using a conversion function.
array.prototype.map will iterate on all items and run a "conversion function" on each item.
Since your item is a key-value that looks like this: {"1":"Input"}, the only problem you have is that you don't know the key.
To get the keys of each object you can use the Object.keys method.
var test=[{"1":"Input"},{"2":"Output"}]; // input
var newArr = test.map(function(item){
var key = Object.keys(item)[0]; // get the object's keys and take the only key.
return {id: key, name: item[key]} // return the new object
});

How to get multiple objects from an array with an id?

I am stuck with Javascript basics.. Working in Angular.
I have an array with objects:
$scope.persons = [
{
id: 1,
name:'jack'
},
{
id: 2,
name:'John'
},
{
id: 3,
name:'eric'
},
{
id: 2,
name:'John'
}
]
I would like to get the all objects that have same id with userId. So, loop through objects if the object id matches to user id select it.
$scope.getResult = function(userId){
$scope.userId = userId;
for(var i=0;i < $scope.persons.length; i++){
if($scope.persons[i].id === $scope.userId){
$scope.result = $scope.persons[i];
}
}
$scope.userLogs = $scope.result;
};
I get here only the last object which has the same id with userId.
How do I list all the objects that have the same id with userId?
Live:http://jsfiddle.net/sb0fh60j/
Thnx in advance!
You can use filter
$scope.getUsers = function(x){
$scope.userId = x;
$scope.userLogs = $scope.persons.filter(function (person) {
return person.id === x;
})
};
Example
Or, in your case, you need declare result as array before loop, and add matches to it, like this
$scope.getUsers = function(x){
$scope.userId = x;
$scope.result = [];
for(var i=0;i < $scope.persons.length; i++){
if($scope.persons[i].id === $scope.userId){
$scope.result.push($scope.persons[i]);
}
}
$scope.userLogs = $scope.result;
};
Example
You are constantly overwriting your result as it is no array. try this instead:
$scope.result[] = $scope.persons[i];
rather than assigning you need to push that object to the array
$scope.result.push($scope.persons[i]);
$scope.result is not an array..
you have to declare a var result = []; and then you can do result.push($scope.persons[i]);
I don't understand why are you using $scope.result, it is useless to instantiate an attribute of the $scope and its watcher for this purpose, imho
edit: is useless also assign x to $scope; added alse a jsfiddle
jsfiddle

Parsing JSON to a regular JavaScript array

How can I load a regular array from a JSON Response like this:
{"project":"8","powerline":"188.396496","road":"7.876766","cost":"69885005.45"}
to
var cars = [8, 188.396496, 7.876766, 69885005.45];
I already tried something like this:
req.done(function(data) {
var cars = JSON.parse(data);
});
but it is not doing the job.
You can simply run a for..in loop like this. and keep pushing the values into a new array.
var obj = {
"project" : "8",
"powerline" : "188.396496",
"road" : "7.876766",
"cost" : "69885005.45"
}
var arr = [];
for (var key in obj) {
var val = parseFloat("0" + obj[key]);
arr.push(val)
}
You can manipulate JSON object as Array, please try this way
req.done(function(data) {
var cars = $.map(JSON.parse(data), function(value, index){
return i;
});
console.log(cars);
});
That's because you're getting an object when you're calling JSON.parse. You can run the following to get the values without keys:
req.done(function (data) {
var jsonData = JSON.parse(data),
cars = []
for (var key in jsonData) {
cars.push(jsonData[key])
}
})

Categories

Resources