How to dynamically add values in JSON array using index - arrays

I am having this format in my script
//declaration of JSON object
items= {};
items.values= [];
I need a structure like this, which is inserted automatically when the script is executed:
items :
{
key :['one', 'two', 'three', 'four'],
values: [1, 2, 3, 4]
}
Since the item.values[0] is undefined, it throws me a undefined error. Can anyone please tell me how to initialize the JSON object, such that it wont throw undefined error
I would like to insert like this:
var i=0;
item.key[i]= 'one';
item.values[i]= 1;
I am not sure whether this is the best practice, if anyone knows better way please post it!
Thanks in advance

You have the right idea. It looks like your property for adding keys isn't there though. Let's declare two properties, keys and values.
items= {};
items.keys = [];
items.values= [];
Our JavaScript object now looks like this
{ "keys": [], "values": [] }
var words = ['one', 'two', 'three', 'four'];
var numbers = [1,2,3,4];
You now want to iterate using a forloop. In JavaScript, arrays are 0-indexed, meaning the first element has an index of 0. That's why we initialize the i variable with a value of 0. After every iteration, we increment this variable and then check if it's less than the length of the array.
function populateObject() {
for (var i = 0; i < words.length; i++) {
items.keys.push(words[i]);
items.values.push(numbers[i]);
}
}
And then call your function
populateObject();
Here is the output
{"keys": ["one", "two", "three", "four"], "values": [1, 2, 3, 4]}

Related

Extract array inside Objects

I am using ReactJS.
I have a JSON:
{
"randomNum1": [
1,
2,
3,
4
],
"randomNum2": [
5,
6,
7,
8
]
}
What I wanted to do is to get the array of randomNum1 and randomNum2. This is what I did:
for(let i = 0; i<data.randomNum1.length; i++)
and I get this error:
Cannot read property 'length' of undefined
The reason why I did that is because when I do a console.log(data.randomNum1) I am able to see the array: [array][1]
Is it because it's still an Object which is why .length is not allowed? If so, how can I get the values of those numbers and store it in an array?
[1]: https://i.stack.imgur.com/nLbdA.png
let allValues=[]
let the_json_object={
"randomNum1": [
1,
2,
3,
4
],
"randomNum2": [
5,
6,
7,
8
]
}
const keys = Object.keys(the_json_object);
const values = Object.values(the_json_object);
let Key_len = keys.length;
for(i=0;i<Key_len;i++){
let len = values[i].length;
for(j=0;j<len;j++)
{
if(values[i][j])
{
allValues.push(values[i][j])
}
}
}
//allValues contains all the values from all arrays.
Your data object is probably undefined at the moment you are entering the loop.
The reason you see it on console.log is because objects are passed by reference. When you console.log the object and then click to see his properties you get the updated object. If you'll do console.log(JSON.stringify(data)) you will see the object is probably empty.
Please provide more code in order to understand the issue here.

Get an array of property values from an object array in typescript

class Test{
constructor(private Name: string, private Id: number, private isAlive: boolean){}
array1?: string[];
}
Imagine that
the array is initialized with a bunch of data from an API response. I have an array of Test objects. What I now need is to extract the Name of all those objects in that array into a new array.
I could not find typescript syntax for this problem.
Typescript is (more or less) a superset of javascript. The same solution for Javascript would apply to Typescript.
const output = input.map( item => item.name );
What I now need is to extract the Name of all those objects in that array into a new array
Use Array.prototype.map : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Fix
From Name[] you want string[]:
const array1: string[] = names.map(x=>x.fieldThatIsTheStringYouWant);
var originalObject = [
{"first":"Gretchen","last":"Kuphal","email":"greenwolf54#gmail.com","address":"416
Lesch Road","created":"March 1, 2012","balance":"$9,782.26"}];
1.you want to copy array simply
var duplicateObject = originalObject;
If you want all you can loop
If you want access one value simply do this
duplicateObject[0].first
alert(duplicateObject[0].first);
Editrd
This can be done also
var originalObject = [
{"first":"Gretchen","last":"Kuphal","email":"greenwolf54#gmail.com","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"salmonsquirrel25#gmail.com","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"Catalina.Daugherty#filomena.name","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"turquoisewolf22#gmail.com","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"Reva.Mohr#oda.net","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"turquoisegiraffe09#gmail.com","address":"84460 Samson Knoll","created":"June 13, 2017","balance":"$9,361.16"}
];
var duplicateObject=new Array();
for (let num of originalObject) {
duplicateObject.push(num.first);
}
// print
for (let first of duplicateObject) {
console.log(first);
}

How to arrange one dictionary array by ascending order and then reorder the other arrays?

I am trying to sort an dictionary (of type [String:[String]]) so that one key is in ascending order, once the key is sorted I would like to sort the other arrays too.
This is what I mean.
var dictionary = ["timeStamp":[String],"condition":[String]] //Dict to sort
dictionary["timeStamp"] = ["123","345","456","234"]
dictionary["condition"] = ["dry","wet","very wet","dry"]
dictionary["timeStamp"] = dictionary["timeStamp"]!.sort()
print("\(dictionary["timeStamp"]!)") //Returns["123","234","345","456"]
How would I be able to sort dictionary["condition"] to be ["dry","dry","wet","very wet"]?
I would make a simple struct so that your properties are associated and can be sorted together
struct condition {
var timeStamp: Int
var description: String
}
var conditionArray = [condition]()
conditionArray.append(condition(timeStamp: 123, description: "dry"))
conditionArray.append(condition(timeStamp: 345, description: "wet"))
conditionArray.append(condition(timeStamp: 456, description: "very wet"))
conditionArray.append(condition(timeStamp: 234, description: "dry"))
let sortedArray = conditionArray.sort() {return $0.timeStamp < $1.timeStamp}
The preferred way is give it a proper structure like #Russel Austin suggested in his answer. But you can also have some fun with Swift higher-order functions:
var dictionary = [
"timeStamp": ["123","345","456","234"],
"condition": ["dry","wet","very wet","dry"]
]
let sorted = Array(0..<dictionary["timeStamp"]!.count)
.map { (timeStamp: dictionary["timeStamp"]![$0], condition: dictionary["condition"]![$0]) }
.sort { $0.timeStamp < $1.timeStamp }
dictionary["timeStamp"] = sorted.map { $0.timeStamp }
dictionary["condition"] = sorted.map { $0.condition }
print(dictionary)
Array(0..<dictionary["timeStamp"]!.count) generate an array of ints, going 0, 1, 2, 3... up to the length of timeStamp
.map { ... } pulls data from the dictionary into tuples of timestamp and condition
.sort{ ... } sorts the array of tuples by the timestamp

How to filter object from array by value and using the value to omit another array or objects?

I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});

Get data from JSON query into javascript array with Array.each

I have results from a Google Geocoder request and I need a value form them to go into another array as follows:
var data = {};
Array.each(results, function(loc)
{
data.['value'] = loc.formatted_address;
}
I need data to then contain this structure:
data = [
{value: 'location one'},
{value: 'location two'},
{value: 'location three'}
];
An example of the JSON results from the query here:
http://maps.googleapis.com/maps/api/geocode/json?address=new%20york&sensor=false
In the case of the example query above the output I want is:
data = [
{value: 'New York, NY, USA'},
{value: 'Manhattan, New York, NY, USA'}
];
Im quite confused about what needs to happen in the Array.each function.
Any help would be great, thanks.
Assuming results contains the results array inside the JSON object above:
var data = [];
for(i = 0; i < results.length; i++)
data.push({'value': results[i].formatted_address});
If results contains the whole JSON object though then you need to write:
results = results.results;
before that loop.

Resources