Javascript - searching object by key - javascript

I know there's plenty of answers on this and most are suggesting looping thru the object, returning what you need, I'm not sure this is the best approach, in my case anyway.
What I have is array with entries referencing to another array people(with id and name) by person_id and projects(with id and name) by project_id.
What I need is to be able to access project and person with a particular id inside the loop on entries, so I can get their names. Doing what others have suggested I'd loop thru people and projects inside each irritation of entries, which seems like awful lot of looping.
So I thought I'd make something I called a "hashtable" from both people and projects on init, which means pretty much creating a new objects people_hashtable and projects_hashtable where key would be the id
so
[
{
"id": "8",
"name": "John Doe"
}
]
would became
{
"8": {
"name": "John Doe"
}
}
this way I'd have easy access to the name without looping all the time while still maintaining the old array with its original order(that's why I'm not outputting it this way directly from server, you can't quite order an object and I'm using both people and projects in a selectbox, which needs to be ordered by name).
Am I doing it right? Are there better way? Or should I forget this completely and stick with the search loop as suggested in other question?
I'm trying to be as efficient as possible on both server and client side.

You basically doubled all the objects just to avoid loop. So, unless you have some bad performance issues, I would avoid that.
In case you really, really need a kind of hashmap, I would prefer storing the array's index instead of another copy of the object:
// array
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
// lookup table
var lookup = {
"8": 0
}
Of course doing that, means you can't modifying the array's without rebuild the hashmap.
Generate it's quite simple:
var lookup = arr.reduce(function(lookup, item, index) {
lookup[item.id] = index;
return lookup;
}, {});
You can also use that to generate the object you mentioned your question:
var lookup = arr.reduce(function(lookup, item) {
lookup[item.id] = {name: item.name};
return lookup;
}, {});
But as I said it's something I would avoid.

Following code may help you. JSFIDDLE
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
var obj = {};
for(var i=0; i< arr.length; i++){
obj[arr[i].id] = {name: arr[i].name};
}
console.log(obj);

var articles= {
"item1":{
"id":"155",
"name":"First Item",
"value":-5199.6
},
"item2":{
"id":"255",
"name":"Second Item",
"value":-424.91
}
}
var ids = [];
for(var item in articles) {
ids.push(articles[item]['id']);
}
console.log(ids);

This lib https://github.com/paularmstrong/normalizr makes it pretty easy to do. Both normalization and denormalization.
It can turn this
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
into this
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
and the other way around.

Related

How can I merge and match 2 separate objects?

What I want
I have 2 different Java-Script arrays/objects but with matching Ids. I want to merge them into a new object. So both the main object data and any matched elements from the secondary object are merged into a combined result.
What I tried
I tried using Object.assign() function but with no success.
Given Input
Example code, so I have 2 separate objects (main and lines):
let main = [
{
"Id": "1",
"Name": "Testing data"
}
]
let lines = [
{
"OtherId": "1",
"code": "AU-29830"
},
{
"OtherId": "1",
"code": "AU-29854-Single"
},
{
"OtherId": "1",
"code": "TV-BB21084623"
},
{
"OtherId": "2",
"code": "Don't Merge"
},
{
"OtherId": "3",
"code": "Don't Merge"
}
]
Expected Output
I want to merge those 2 arrays, so that the output should be a single array containing the merged main-object. This merged main-object should contain the original content of itself plus nested the filtered secondary array (only containing matching objects). The filtering was done using the id from the main array's object which has to match (the slightly deviating id) from each object of the secondary-array.
The resulting array should look like this:
let result = [
{
"Id": "1",
"Name": "Testing data",
"lines": [
{
"OtherId": "1",
"ProductCode": "AU-29830"
},
{
"OtherId": "1",
"ProductCode": "AU-29854-Single"
},
{
"OtherId": "1",
"ProductCode": "TV-BB21084623"
}
]
}
]
As your main is an array, I'm assuming you might end up with more than one main item in it. If so, here's one way to merge your line items onto each one:
const mergedMainItems =
main.map(mainItem=>({
...mainItem,
lines: lines.filter(line=>mainItem["Id"] === line["OtherId"])
}))
I think for this example this will work:
let result = [];
result.push({...main[0]}); //or even result.push(main[0])
result[0].lines = [];
for(let l in lines){
if(lines[l].code != "Don't Merge"){
result[0].lines.push({OtherId: lines[l].OtherId, ProductCode: lines[l].code})
}
}

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

How to get an array inside an array?

Hi I have trouble with an array response of json.
I'm supposed to get the members of the objects. but that array is inside another array.
This is the array that is being returned.
var arr = [
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
],
[
{
"id": 4243430854,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666182,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644294,
"email": "kfsucayan#gmail.com",
}
]
];
How can i dig down to the values? before I would use arr[i].email, but now it doesn't work. I've tried arr[0].[i].email, but returns be the error missing name after . operator. Is there a way that I can remove that outer array?
It should be arr[i][j].email. i to loop over the array arr itself and j to loop over each sub-array.
arr[i] will give you something like this (if i == 0 for example):
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
]
and then arr[i][j] will give something like this (if i == 0 and j == 2):
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
then you can access the email property using arr[i][j].email.
There's two ways to access objects in Javascript: using periods or using square brackets. Here, you're trying to mix the two, which works, but probably isn't the best practice. You should pick whichever is best for the situation. Here, you'd want to use the brackets:
arr[i][j]["email"];
Note that when using variables, you will always need to use brackets as opposed to periods.

Copying/Rename JSON Object Array

Am getting Data from server in below JSON format
{
"Data": [
{
"Id": "1",
"Number": 0,
"Modify": {
"Id": 0,
"Name": "a"
}
},
{
"Id": "2",
"Number": 1,
"Modify": {
"Id": 1,
"Name": "b"
}
}
]}
And am trying to create a new copy(Rename) of Modify inside the same object because my other data is expecting JSON with same format but different name for modify.
So i though i would foreach and create copy of the same which will form like below
{
"Data": [
{
"Id": "1",
"Number": 0,
"Modify": {
"Id": 0,
"Name": "a"
},"New": {
"Id": 0,
"Name": "a"
}
},
{
"Id": "2",
"Number": 1,
"Modify": {
"Id": 1,
"Name": "b"
},
"New": {
"Id": 1,
"Name": "b"
}
}
]}
Is there a better approach i can rename the object or should i create a copy. What is the better way to copy ?
Thanks
For loop is a fine way to do that.. data[i].Name = data[i].Modify;. Im fairly sure there isn't a "better" way than this in Javascript.
There's no other way than the one suggested by #MjrKusanagi, nevertheless I suggest another approach.
Make a function that takes your original object and replaces the selected key with the new name, returning a new object without changing the original one (immutability)
The function could take 3 arguments:
function modifyObject(object, oldKey, newKey) {...}
Inside the function you could use the Object.assign method to create a copy of the original object (a copy, not a reference):
var newObj = Object.assign({}, object);
After that, you can change the key name by creating a new one and don't forget to remove old key from the new object:
newObj.newKey = newObj.oldKey;
delete newObj.oldKey,
Finally you can return this new object and even use this function every time you need to do anything similar.
Using the delete is considered bad practice, but at least here you are not mutating your original source, so you can depend in its content over all your application's life cycle.

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

Categories