javascript array of object with key - javascript

I've been searching and searching and haven't found a solution...even though, likely, it's simple. How do I create something that will give me this:
myArray['key1'].FirstName = "First1";
myArray['key1'].LastName = "Last1";
myArray['key2'].FirstName = "First2";
myArray['key2'].LastName = "Last2";
myArray['key3'].FirstName = "First3";
myArray['key3'].LastName = "Last3";
And then say something like, alert(myArray['key2'].FirstName);
And will I be able to iterate through it like:
for(i=0; i < myArray.length; i++){
//do whatever
}
Thanks in advance!

You can init an object something like that:
{
"key1": {FirstName: "first1", LastName: "last1"}
"key2": {FirstName: "first2", LastName: "last2"}
"key3": {FirstName: "first3", LastName: "last3"}
}
Sample function for init your array:
function initArray(){
for(var i=1; i< count+1; i++) {
var newElement = {}
newElement.FirstName = "first" + i;
newElement.LastName = "last" + i;
var keyName = "key" + i
var obj = {};
myArray[keyName] = newElement
}
}
Now "myArray["key2"] is accessible.
http://jsfiddle.net/jq5Cf/18/

You can't do what you're trying to do in javascript! (because javascript can't do associative arrays)
I would go for an object which has an internal array to store other things
var container = {};
container.things = [];
container.things.push({FirstName: 'First1', LastName: 'Last1'});
now you can do..
for(var i in container.things) {
alert(container.things[i].FirstName);
}

In JavaScript we use arrays like this, [] for Arrays and Objects are in {}
var MyArray = [
{FirstName: "Firsname1" , LastName: "Lasname1"},
{FirstName: "Firsname2" , LastName: "Lasname2"}
]

Your myarray variable construction is in notation of objects of objects.
var myArray = {'key1':
{
'FirstName' : "First1",
'LastName' : "Last1"
}};
In order to access the values should be like array of objects.
var myArray = [
{
'FirstName' : "First1",
'LastName' : "Last1"
},
];
or notation can be like below:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};

Related

React - Filter JSON array if key exists [duplicate]

I have an array of objects and I'm wondering the best way to search it. Given the below example how can I search for name = "Joe" and age < 30? Is there anything jQuery can help with or do I have to brute force this search myself?
var names = new Array();
var object = { name : "Joe", age:20, email: "joe#hotmail.com"};
names.push(object);
object = { name : "Mike", age:50, email: "mike#hotmail.com"};
names.push(object);
object = { name : "Joe", age:45, email: "mike#hotmail.com"};
names.push(object);
A modern solution with Array.prototype.filter():
const found_names = names.filter(v => v.name === "Joe" && v.age < 30);
Or if you still use jQuery, you may use jQuery.grep():
var found_names = $.grep(names, function(v) {
return v.name === "Joe" && v.age < 30;
});
You can do this very easily with the [].filter method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You can learn more about it on this MDN page.
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [
{ name : "Joe", age:20, email: "joe#hotmail.com"},
{ name : "Mike", age:50, email: "mike#hotmail.com"},
{ name : "Joe", age:45, email: "mike#hotmail.com"}
];
var filteredNames = $(names).filter(function( idx ) {
return names[idx].name === "Joe" && names[idx].age < 30;
});
$(filteredNames).each(function(){
$('#output').append(this.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"/>
var nameList = [
{name:'x', age:20, email:'x#email.com'},
{name:'y', age:60, email:'y#email.com'},
{name:'Joe', age:22, email:'joe#email.com'},
{name:'Abc', age:40, email:'abc#email.com'}
];
var filteredValue = nameList.filter(function (item) {
return item.name == "Joe" && item.age < 30;
});
//To See Output Result as Array
console.log(JSON.stringify(filteredValue));
You can simply use javascript :)
For those who want to filter from an array of objects using any key:
function filterItems(items, searchVal) {
return items.filter((item) => Object.values(item).includes(searchVal));
}
let data = [
{ "name": "apple", "type": "fruit", "id": 123234 },
{ "name": "cat", "type": "animal", "id": 98989 },
{ "name": "something", "type": "other", "id": 656565 }]
console.log("Filtered by name: ", filterItems(data, "apple"));
console.log("Filtered by type: ", filterItems(data, "animal"));
console.log("Filtered by id: ", filterItems(data, 656565));
filter from an array of the JSON objects:**
var names = [{
name: "Joe",
age: 20,
email: "joe#hotmail.com"
},
{
name: "Mike",
age: 50,
email: "mike#hotmail.com"
},
{
name: "Joe",
age: 45,
email: "mike#hotmail.com"
}
];
const res = _.filter(names, (name) => {
return name.name == "Joe" && name.age < 30;
});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
So quick question. What if you have two arrays of objects and you would like to 'align' these object arrays so that you can make sure each array's objects are in the order as the other array's? What if you don't know what keys and values any of the objects inside of the arrays contains... Much less what order they're even in?
So you need a 'WildCard Expression' for your [].filter, [].map, etc. How do you get a wild card expression?
var jux = (function(){
'use strict';
function wildExp(obj){
var keysCrude = Object.keys(obj),
keysA = ('a["' + keysCrude.join('"], a["') + '"]').split(', '),
keysB = ('b["' + keysCrude.join('"], b["') + '"]').split(', '),
keys = [].concat(keysA, keysB)
.sort(function(a, b){ return a.substring(1, a.length) > b.substring(1, b.length); });
var exp = keys.join('').split(']b').join('] > b').split(']a').join('] || a');
return exp;
}
return {
sort: wildExp
};
})();
var sortKeys = {
k: 'v',
key: 'val',
n: 'p',
name: 'param'
};
var objArray = [
{
k: 'z',
key: 'g',
n: 'a',
name: 'b'
},
{
k: 'y',
key: 'h',
n: 'b',
name: 't'
},
{
k: 'x',
key: 'o',
n: 'a',
name: 'c'
}
];
var exp = jux.sort(sortKeys);
console.log('#juxSort Expression:', exp);
console.log('#juxSort:', objArray.sort(function(a, b){
return eval(exp);
}));
You can also use this function over an iteration for each object to create a better collective expression for all of the keys in each of your objects, and then filter your array that way.
This is a small snippet from the API Juxtapose which I have almost complete, which does this, object equality with exemptions, object unities, and array condensation. If these are things you need or want for your project please comment and I'll make the lib accessible sooner than later.
Hope this helps! Happy coding :)
The most straightforward and readable approach will be the usage of native javascript filter method.
Native javaScript filter takes a declarative approach in filtering array elements. Since it is a method defined on Array.prototype, it iterates on a provided array and invokes a callback on it. This callback, which acts as our filtering function, takes three parameters:
element — the current item in the array being iterated over
index — the index or location of the current element in the array that is being iterated over
array — the original array that the filter method was applied on
Let’s use this filter method in an example. Note that the filter can be applied on any sort of array. In this example, we are going to filter an array of objects based on an object property.
An example of filtering an array of objects based on object properties could look something like this:
// Please do not hate me for bashing on pizza and burgers.
// and FYI, I totally made up the healthMetric param :)
let foods = [
{ type: "pizza", healthMetric: 25 },
{ type: "burger", healthMetric: 10 },
{ type: "salad", healthMetric: 60 },
{ type: "apple", healthMetric: 82 }
];
let isHealthy = food => food.healthMetric >= 50;
const result = foods.filter(isHealthy);
console.log(result.map(food => food.type));
// Result: ['salad', 'apple']
To learn more about filtering arrays in functions and yo build your own filtering, check out this article:
https://medium.com/better-programming/build-your-own-filter-e88ba0dcbfae

create an array of objects from an object and array

I have an object:
items = {
0: "foo",
1: "bar",
2: "baz"
};
and an array:
category = [
"type1",
"type2",
"type3"
];
I want to merge these with the desired output:
newArray = [
{type1:"foo"},
{type2:"bar"},
{type3:"baz"}
];
I thought I would be able to do it quite simply with a for loop like the following (though any method would do):
var obj = {};
for (var i = 0; i < category.length; i++) {
obj [category[i]] = items[i];
newArray.push(obj);
}
What I actually get is :
[{"type1":"foo","type2":"bar","type3":"baz"},
{"type1":"foo","type2":"bar","type3":"baz"},
{"type1":"foo","type2":"bar","type3":"baz"}]
I guess it's iterating through all instances of i for each obj each time but how do I amend to get the desired output?
https://jsfiddle.net/ormxq0y4/3/
you want a new object for each iteration
for (var i = 0; i < category.length; i++) {
var obj = {};
obj [category[i]] = items[i];
newArray.push(obj);
}
I guess this should do it;
var items = {
0: "foo",
1: "bar",
2: "baz"
},
category = [
"type1",
"type2",
"type3"
],
newArray = category.map((e,i) => ({[e]:items[i]}));
console.log(newArray)
You could try something like this ->
category.forEach(function (e,i) {
var obj = {};
obj[e] = items[i];
newArray.push(obj);
});
var items = {
0: "foo",
1: "bar",
2: "baz"
},
category = [
"type1",
"type2",
"type3"
];
var reformattedArray = category.map(function(obj, index){
var rObj = {};
rObj[obj] = items[index];
return rObj;
});
console.log("reformattedArray", reformattedArray);
https://jsfiddle.net/s6ntL2eo/
Here is how i would do it. But in my honest opinion is a bit risky if you relay only on the items KEY to be the connection point for the array. Please also keep in mind that an object allows the key to be eigther string or number (that's why items[+key]).
var items = {
0: "foo",
1: "bar",
2: "baz"
};
var categories = [
"type1",
"type2",
"type3"
];
var newArray = [];
categories.forEach(function (category, key) {
if (items[+key]) {
var tmpO = {};
tmpO[category] = items[+key];
newArray.push(tmpO);
}
});
console.log(newArray)
You are not making a separate object each time. Instead you are pushing the same object three times, and adding type1, type2, type3 properties to this one object.
Simply moving var obj = {} into the loop fixes your issue.
newArray = [];
items = {
0: "foo",
1: "bar",
2: "baz"
};
category = [
"type1",
"type2",
"type3"
];
for (var i = 0; i < category.length; i++) {
var obj = {};
obj[category[i]] = items[i];
newArray.push(obj);
}
var title = document.getElementById("title");
title.innerHTML = JSON.stringify(newArray);
With the result: [{"type1":"foo"},{"type2":"bar"},{"type3":"baz"}]

How to convert two arrays to a key-value pair and append them to an array

I am working on a project in which I need an array like this:
user = [{
"name": "foo",
"email": "foo#foo.com"
},{
"name": "bar",
"email": "bar#bar.com"
},]
the values name and email are in two separate arrays, like:
names=[foo,bar];
mails=[foo#foo.com,bar#bar.com]
How do I convert these two arrays in a single array of objects with predefined keys name and email?
I am trying something like this:
var user = [];
for(var i=0; i<names.length; i++) {
user[i].name = names[i];
user[i].email = mails[i];
}
but this raises an error that name property is not defined.
You just have to push an object composed of mames and email this way
var names=["foo","bar"];
var mails=["foo#foo.com","bar#bar.com"];
var users = [];
for(var i=0; i<names.length; i++) users.push({"name" : names[i], "email" : mails[i]});
console.log(users);
Run:
[ { name: 'foo', email: 'foo#foo.com' },
{ name: 'bar', email: 'bar#bar.com' } ]

Old JSON value Changed

I have two JSON objects columnsData and columns when assigning columnsData value to columns both values are changed.
var columnsData = [
{id: "id"},
{id: "root_task_assignee"},
{id: "root_task_id"},
{id: "root_task_status"},
{id: "root_task_tracker"},
{id: "rt_category"},
{id: "rt_priority"},
{id: "rt_subject"},
]
var columns = [];
using the below function I assigned the columnsData value to columns object, and also added some additional fields
for(i = 0;i < columnsData.length; i++){
columns[i] = columnsData[i];
columns[i]["name"] = columnsData[i]["name"] || columnsData[i]["id"];
columns[i]["type"] = columnsData[i]["id"]["type"] || "string";
}
but after assigning both have the same values. How the old JSON columnsData value was changed? is there any other way to assign values
columns[i] = columnsData[i] does not copy the data, it makes an additional reference to the same data.
For example, say you give Mr. Random Jones a nickname, "Cozy". If you give Cozy an envelope to hold, are you surprised if Mr. Jones is now holding an envelope too?
Same thing here. If you change columns[i], you are also changing columnsData[i], since they are the same object.
You would have to clone it if you wanted to have them be different. In this case, you just have to make a new object with id:
columns[i] = { id: columnsData[i].id };
In general, you would do well to find a nice clone function.
If it is required to keep original array pure (unchanged) we should use map method of array.
var columnsData = [
{id: "id"},
{id: "root_task_assignee"},
{id: "root_task_id"},
{id: "root_task_status"},
{id: "root_task_tracker"},
{id: "rt_category"},
{id: "rt_priority"},
{id: "rt_subject"},
]
var columns = columnsData.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
rObj["name"] = obj.value;
.....
return rObj;
});
Logic can be added in map method to create new array as required. Hope it helps.
columns[i] = columnsData[i] will not copy content from one object to another but it will an reference of the columnsData[i]. As they are refereeing to same object, change in property of one object will affect the primary object which is being refereed.
Try this:
var columnsData = [{
id: "id"
}, {
id: "root_task_assignee"
}, {
id: "root_task_id"
}, {
id: "root_task_status"
}, {
id: "root_task_tracker"
}, {
id: "rt_category"
}, {
id: "rt_priority"
}, {
id: "rt_subject"
}, ]
var columns = [];
for (i = 0; i < columnsData.length; i++) {
var obj = {};
obj["name"] = columnsData[i]["name"] || columnsData[i]["id"];
obj["type"] = columnsData[i]["id"]["type"] || "string";
columns.push(obj)
}
alert(JSON.stringify(columns));
alert(JSON.stringify(columnsData));

Turning an array into an array of objects with Underscore.js?

I have an array:
var countries = ['Austria', 'America', 'Australia'];
I know you can turn that into an object with Underscore.js like this:
_.object(['name', 'name2', 'name3'], countries));
How can I turn the array into an array of objects that looks like this?
var countriesObject = [
{ name: 'Austria' },
{ name: 'America' },
{ name: 'Australia' }
];
(with all the keys named name).
No need to use Underscore.js for that. You can do it with plain javascript:
var new_arr = [];
countries.forEach(function(country) {
var new_obj = {};
new_obj.name = country;
new_arr.push(new_obj);
});
console.table(new_arr);
var countriesObject = _.map (countries,function (country){
return {
name: country
}
}

Categories

Resources