Adding object properties from one JSON data file to another - javascript

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.
Here is an example..
Array1:
[
{
"id": 1,
"username": "Joe Smith",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 2,
"username": "Jane Smith",
"pic": "images/profile/Jane_smith.jpg"
}
]
Array2:
[
{
"id": 3,
"userId": 1,
"profession": "dentist"
},
{
"id": 4,
"userId": 2,
"profession": "pilot"
}
The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:
[
{
"id": 3,
"userId": 1,
"profession": "dentist",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 4,
"userId": 2,
"profession": "pilot",
"pic": "images/profile/Jane_smith.jpg"
}
Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!

Just for the fun of it. In this example using https://lodash.com.
var people = [
{ "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" },
{ "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
{ "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];
var professions = [
{ "id": 3, "userId": 1, "profession": "dentist" },
{ "id": 4, "userId": 2, "profession": "pilot" }
];
var workers = _.map(people, function(human) {
var work = _.findWhere(professions, { 'userId': human.id });
return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});
console.log(workers);

Related

Object with nested array to filter, want to return entire object with new filtered array

I'm attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
and what I'm doing right now is
const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);
but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
I've tried reading around but I'm not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!
If you want to mutate the existing object, just assign the result of the .filter to the .actors property.
movie.actors = movie.actors.filter((actor) => actor.id !== id);
console.log(movie);
If you want to keep the existing object unmutated, spread the rest of the properties into a new object while filtering.
const updatedMovie = {
...movie,
actors: movie.actors.filter((actor) => actor.id !== id)
};
console.log(updatedMovie);
const movies = {
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
const id = 3; // or any other id you want
const actors = movies.actors.filter(actor => actor.id != id)
const newMovies = Object.assign({}, movies , { actors })
console.log(newMovies)

Knexnest query not returning data in array even though this is what is expected

I have this knexnest query:
const query = knex.select([
'notes.id AS _id',
'notes.note AS _note',
'notes.timestamp AS _timestamp',
'customers.id AS _customerId',
'users.name AS _name',
'products.id AS _productId',
'tags.id AS _tags_tagId',
'tags.title AS _tags_tagTitle',
'tags.type AS _tags_tagType',
]).from('notes')
.join('users', 'notes.user_id', 'users.id')
.join('customers', 'notes.customer_id', 'customers.id')
.leftJoin('products', 'notes.product_id', 'products.id')
.leftJoin('note_tags', 'notes.id', 'note_tags.note_id')
.leftJoin('tags', 'note_tags.tag_id', 'tags.id')
.where('customers.id', customerId);
return knexnest(query);
My response json looks like this:
{
"id": 47,
"note": "This is an updated1 note",
"timestamp": "2019-07-12T15:17:27.281Z",
"customerId": 111781,
"name": "Paul",
"productId": 1,
"tags": {
"tagId": 4,
"tagTitle": "price",
"tagType": "product"
}
}
The problem is that the database returns more than one tag, only one is displayed. I'm expecting a response like this:
{
"id": 47,
"note": "This is an updated1 note",
"timestamp": "2019-07-12T15:17:27.281Z",
"customerId": 111781,
"name": "Paul",
"productId": 1,
"tags": {[
{
"tagId": 4,
"tagTitle": "price",
"tagType": "product"
},
{
"tagId": 5,
"tagTitle": "quality",
"tagType": "product"
}
]}
}
Have I got something wrong in my query that is causing this?
Got it. I was missing double __ in the tags:
'tags.id AS _tags__tagId',
'tags.title AS _tags__tagTitle',
'tags.type AS _tags__tagType'

Return array of data instead of Dictionary - Sequelize

I need post data like array, but I send it always like this:
{
"books": [
{
"id": 19,
"name": "Král Lávra",
"author": "Karel Havlíček Borovský",
"yearOfRelease": "1920",
"price": "120",
"SubjectId": 1,
"UserId": 2,
"SchoolId": 1
},
]
}
I want show result like this:
[
{
"id": 19,
"name": "Král Lávra",
"author": "Karel Havlíček Borovský",
"yearOfRelease": "1920",
"price": "120",
"SubjectId": 1,
"UserId": 2,
"SchoolId": 1
},
]
I use sequelize to connection between database MySQL. This is my code for findAll books:
let books = await ctx.db.Book.findAll({
where: {
UserId: id
},
})
Then I only post to
ctx.body= {
books
}
Thanks for your response.

Display json data in spreadsheet like looking html table using angular

I need help regarding rendering this JSON data in html table using angular:
[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}]
My rendered html table should look like this
Test1 Test2
John 20 50
Doug 10 100
Somehow values need to be grouped by, and then rendered, but to keep matching data. Also that first position in array[0][0] should be empty. Any help will be appreciated.
So you can group your data by name , and have Object of arrays like following :
{
"John": [
{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test2",
"number": 50,
"name": "John"
}
],
"Doug": [
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}
]
}
Then , define a function to retrieve data by name & task : getItemBy=function(name,task)
Those two steps will make your algo easy to render HTML table as u want :
DEMO :
var data=[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}];
var groupBy=function(arr,key) {
return arr.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
//------
var groupedByName=groupBy(data,'name');
var getItemBy=function(name,task){
return groupedByName[name].filter((item)=>item.task===task)
};
//------
//--
console.log(`***** Item where name=John & task=Test1`,
getItemBy('John','Test1')
)
console.log(`****** All data after grouping`,
groupedByName
)

Returning a new JSON object with filtered results

I'm looking to return a new JS object from an existing JS object, after filtering for some result.
Say I have the following JS object:
{ "Examples" :
[ { "id": 1, "name": "Tim", "answer": "yes"},
{ "id": 2, "name": "Jon", "answer": "no"},
{ "id": 3, "name": "Don", "answer": "yes" ] }
I want to filter through this object for all yes answers and return an object that looks like this:
{ "Examples" :
[ { "id" : 1, "name": "Tim", "answer": "yes"},
{ "id" : 3, "name": "Don", "answer": "yes"} ] }
First: that's a JavaScript object, not a JSON object. JSON is a serialization scheme.
You can filter the array with .filter():
var obj = { "Examples" :
[ { "id": 1, "name": "Tim", "answer": "yes"},
{ "id": 2, "name": "Jon", "answer": "no"},
{ "id": 3, "name": "Don", "answer": "yes" ] };
obj.Examples = obj.Examples.filter(function(entry) {
return entry.answer === "yes";
});

Categories

Resources