convert Json into a JS object - javascript

id like to create an new object "formattedCharacters" from the object data.
I need to capture every ID and filter the elements id, name, image, species, gender, location and status but I am unable to pass the data into the new object.
My idea was to pass the object to an array using object values, and then use for each to pass every element into my new array of objects, nevertheless I have been unable to do it.
Could you please help assesing why this isnt working and any tips on what should I try?
// Json data example
function getCharacters() {
const data = {
info: {
count: 671,
pages: 34,
next: 'https://rickandmortyapi.com/api/character?page=2',
prev: null,
},
results: [{
id: 1,
name: 'Rick Sanchez',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Male',
origin: {
name: 'Earth (C-137)',
url: 'https://rickandmortyapi.com/api/location/1',
},
location: {
name: 'Earth (Replacement Dimension)',
url: 'https://rickandmortyapi.com/api/location/20',
},
image: 'https://rickandmortyapi.com/api/character/avatar/1.jpeg',
episode: [
'https://rickandmortyapi.com/api/episode/1',
'https://rickandmortyapi.com/api/episode/2',
],
url: 'https://rickandmortyapi.com/api/character/1',
created: '2017-11-04T18:48:46.250Z',
},
{
id: 2,
name: 'Morty Smith',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Male',
origin: {
name: 'Earth (C-137)',
url: 'https://rickandmortyapi.com/api/location/1',
},
location: {
name: 'Earth (Replacement Dimension)',
url: 'https://rickandmortyapi.com/api/location/20',
},
image: 'https://rickandmortyapi.com/api/character/avatar/2.jpeg',
episode: [
'https://rickandmortyapi.com/api/episode/1',
'https://rickandmortyapi.com/api/episode/2',
......
// here is the problem
const formatedCharcters = data.results
formatedCharcters.forEach(character => {
return {
id: character.id
name: character.name
status: character.status
species: character.species
gender: character.gender
location: character.location.name
image: character.image
}
})
return formatedCharcters;
}
const characters = getCharacters();

You will want to use something like map instead
This is a simply change to your code:
formatedCharcters = data.results.map(character => {

Here's a guess of what you're trying to achieve. I think you're trying to map data into objects with a forEach loop. Sadly this is not possible with forEach , but rather with the map function instead. Let me know if this is what you wanted. I am willing to edit my answer depending on any other details.
const results = [{
id: 1,
name: 'Rick Sanchez',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Male',
origin: {
name: 'Earth (C-137)',
url: 'https://rickandmortyapi.com/api/location/1',
},
location: {
name: 'Earth (Replacement Dimension)',
url: 'https://rickandmortyapi.com/api/location/20',
},
image: 'https://rickandmortyapi.com/api/character/avatar/1.jpeg',
episode: [
'https://rickandmortyapi.com/api/episode/1',
'https://rickandmortyapi.com/api/episode/2',
],
url: 'https://rickandmortyapi.com/api/character/1',
created: '2017-11-04T18:48:46.250Z',
},
{
id: 2,
name: 'Morty Smith',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Male',
origin: {
name: 'Earth (C-137)',
url: 'https://rickandmortyapi.com/api/location/1',
},
location: {
name: 'Earth (Replacement Dimension)',
url: 'https://rickandmortyapi.com/api/location/20',
},
image: 'https://rickandmortyapi.com/api/character/avatar/2.jpeg',
episode: [
'https://rickandmortyapi.com/api/episode/1',
'https://rickandmortyapi.com/api/episode/2',
],
url: 'https://rickandmortyapi.com/api/character/1',
created: '2017-11-04T18:48:46.250Z',
}]
function getCharacters() {
const charachters = results.map(character => {
return {
id: character.id,
name: character.name,
status: character.status,
species: character.species,
gender: character.gender,
location: character.location.name,
image: character.image,
};
});
return charachters;
}
console.log(getCharacters());

I am not sure that I completely understand your question, but here is one way you could achieve the result you are probably looking for. I have kept the forEach loop in case there is a specific reason for keeping it:
// Json data example
function getCharacters() {
const data = {
info: {
count: 671,
pages: 34,
next: 'https://rickandmortyapi.com/api/character?page=2',
prev: null,
},
results: [
{
id: 1,
name: 'Rick Sanchez',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Male',
origin: {
name: 'Earth (C-137)',
url: 'https://rickandmortyapi.com/api/location/1',
},
location: {
name: 'Earth (Replacement Dimension)',
url: 'https://rickandmortyapi.com/api/location/20',
},
image: 'https://rickandmortyapi.com/api/character/avatar/1.jpeg',
episode: [
'https://rickandmortyapi.com/api/episode/1',
'https://rickandmortyapi.com/api/episode/2',
],
url: 'https://rickandmortyapi.com/api/character/1',
created: '2017-11-04T18:48:46.250Z'
},
{
id: 2,
name: 'second name',
status: 'Alive',
species: 'Human',
type: '',
gender: 'Female',
origin: {
name: 'Mars???',
url: 'sample-url.com/sample/example',
},
location: {
name: 'Mars??? (Replacement Dimension)',
url: 'sample-url.com/sample/example',
},
image: 'sample-url.com/sample/example',
episode: [
'sample-url.com/sample/example',
'sample-url.com/sample/example',
],
url: 'sample-url.com/sample/example',
created: '2019-12-04T11:48:46.250Z'
}
]
}
// here is the problem
const formattedCharacters = data.results;
const character_array = [];
formattedCharacters.forEach(character=>{
//here instead of returning multiple times, just push value into an array
character_array.push({
id: character.id,
name: character.name,
status: character.status,
species: character.species,
gender: character.gender,
location: character.location.name,
image: character.image
});
})
return character_array;
}
const characters = getCharacters();
// therefore:
const character_1 = characters[0];
console.log(character_1);
The above would produce an array of all the elements inside of data.results with the values you need.
Hope that helped, AlphaHowl.

Related

Replace the records of particular category

There is one scenario where i need to replace the existing records from cached data with new incoming data source. Looking for the cleaner approach to handle the array operations.
For example:
var userCategory = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'bar',
},
{
id: 'platinum',
name: 'foo',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
Here is new users of particular category
var newPlatinumUsers = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
];
This is the expected result needed:
var expected = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
I tried with filtering all the platinum user from existing records then added the new records but it looks verbose
Is there any cleaner approach like lodash operator??
Thanks for your time!!!
May you are looking for this.
function getUnique(arr){
// removing duplicate
let uniqueArr = [...new Set(arr)];
document.write(uniqueArr);
}
const array = ['acer','HP','Apple','Apple','something'];
// calling the function
getUnique(array);
Verify my answer if it help you.
Please find the Javascript implementation of the same
var userCategory = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'bar', },
{ id: 'platinum', name: 'foo', },
{ id: 'gold', name: 'tom', },
{ id: 'silver', name: 'billy', },
];
var newPlatinumUsers = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'mike', },
];
const result = [...newPlatinumUsers];
userCategory.forEach((node) => {
if(node.id !== 'platinum') {
result.push(node);
}
});
console.log(result);
With this solution you can change more than one category:
var userCategory = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'bar'},
{id: 'platinum',name: 'foo'},
{id: 'gold',name: 'tom'},
{id: 'silver',name: 'billy'},
];
var newUsers = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'mike'},
{id: 'gold',name: 'will'},
{id: 'gold',name: 'jerry'},
];
const idsToReplace = {}
const result = [...newUsers]
result.forEach(u => {
idsToReplace[u.id] = true
})
userCategory.forEach(u => {
if(!idsToReplace[u.id]){
result.push(u)
}
})
console.log(result)

React.js: How to compare data from 2 objects of arrays?

I have an array of objects displayed on the UI. Now I want to change the style of the data which doesn't match with the data from another array of objects.
Basically my goal is to create a boolean data which checks if the data are matching for both array of objects, and according to this boolean data the style will be changed.
Here is what I have.
And codesandbox link
import React from "react";
import "./styles.css";
const result1 = [
{ id: 1, name: "Sandra", type: "user", username: "sandra" },
{ id: 2, name: "John", type: "admin", username: "johnny2" },
{ id: 3, name: "Peter", type: "user", username: "pete" },
{ id: 4, name: "Bobby", type: "user", username: "be_bob" },
{ id: 5, name: "Bob", type: "user", username: "bob" },
{ id: 6, name: "James", type: "user", username: "james" },
{ id: 7, name: "Bill", type: "user", username: "bill" }
];
const result2 = [
{ id: 2, name: "John", username: "johnny2" },
{ id: 5, name: "Bob", type: "user", username: "bob" },
{ id: 4, name: "Bobby", username: "be_bob" }
];
export default function App() {
const excludedPerson = result1.filter(
(person1) => !result2.some((person2) => person1.name === person2.name)
);
console.log(excludedPerson);
return (
<div className="App">
{result1.map((person) => (
<ul key={person.id}>
<div>{person.name}</div>
<div
style={{
textDecoration: "boolean" ? "line-through" : "none" // instead of string it should be a boolean
}}
>
{person.username}
</div>
</ul>
))}
</div>
);
}
Instead of using filter you can use map and get the boolean excludedPerson array
changes:
1) use map instead of filter
const excludedPerson = result1.map(
(person1) => !result2.some((person2) => person1.name === person2.name)
);
2) Add second parameter in JSX i.e index
{result1.map((person, i) => (
3) change CSS styles accordingly: I've strike through the result1 elements that are not in result2
textDecoration: !excludedPerson[i] ? "line-through" : "none"
CODE DEMO
import React from "react";
import "./styles.css";
const result1 = [
{ id: 1, name: "Sandra", type: "user", username: "sandra" },
{ id: 2, name: "John", type: "admin", username: "johnny2" },
{ id: 3, name: "Peter", type: "user", username: "pete" },
{ id: 4, name: "Bobby", type: "user", username: "be_bob" },
{ id: 5, name: "Bob", type: "user", username: "bob" },
{ id: 6, name: "James", type: "user", username: "james" },
{ id: 7, name: "Bill", type: "user", username: "bill" }
];
const result2 = [
{ id: 2, name: "John", username: "johnny2" },
{ id: 5, name: "Bob", type: "user", username: "bob" },
{ id: 4, name: "Bobby", username: "be_bob" }
];
export default function App() {
const excludedPerson = result1.map(
(person1) => !result2.some((person2) => person1.name === person2.name)
);
console.log(excludedPerson);
return (
<div className="App">
{result1.map((person, i) => (
<ul key={person.id}>
<div>{person.name}</div>
<div
style={{
textDecoration: !excludedPerson[i] ? "line-through" : "none" // instead of string it should be a boolean
}}
>
{person.username}
</div>
</ul>
))}
</div>
);
}
Mabye something like this? Return only the common objects in the two array of objects
const result1 = [
{ id: 1, name: 'Sandra', type: 'user', username: 'sandra' },
{ id: 2, name: 'John', type: 'admin', username: 'johnny2' },
{ id: 3, name: 'Peter', type: 'user', username: 'pete' },
{ id: 5, name: 'Bob', type: 'user', username: 'bob' },
{ id: 6, name: 'James', type: 'user', username: 'james' },
{ id: 7, name: 'Bill', type: 'user', username: 'bill' },
];
const result2 = [
{ id: 2, name: 'John', username: 'johnny2' },
{ id: 5, name: 'Bob', type: 'user', username: 'bob' },
{ id: 4, name: 'Bobby', username: 'be_bob' },
];
const output = result1.filter(({ id: id1 }) =>
result2.some(({ id: id2 }) => id2 === id1)
);
console.log(output);

Parse js table from the file

I write a programe in JavaScript where I want to add file "tables.js". There are many tables saved in this file.I want to validate the data in each table.
How can I save each of these tables as a separate variable? var people = ...; var city = ...
Part of tables.js file below.
{
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent:'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent:'Europe'
}]
}
I have tried JSON.parse so far but unfortunately I can't split this file into separate tables.
What you have to do is extract from the object Keys and allocate them to new variables
There are two ways of doing this . One is dot Notations as per the example and the other is bracket notation which looks like this
let people = data['people'];
let city= data['city'];
var data = {
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent:'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent:'Europe'
}]
};
let people = data.people;
let city = data.city;
console.log(people)
console.log('=================')
console.log(city)
Same as above but with ES6 (latest JS version) constants and deconstruct features.
const data = {
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent: 'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent: 'Europe'
}]
}
const {people, city} = data
console.log('People:', people)
console.log('City:', city)

Get path of an object tree

EDIT: I've updated the data structure and new test here: http://jsfiddle.net/6Lwrsjou/5/ images2 is being nested under images, which it shouldn't be.
I have an array that contains objects like this:
var objects = [{
_id: 1,
name: 'images',
type: 'directory',
children: [{
_id: 2,
name: 'set 2',
type: 'directory',
children: [{
_id: 3,
name: 'image.jpg',
type: 'file'
},
{
_id: 4,
name: 'image2.jpg',
type: 'file'
},
{
_id: 5,
name: 'set 3',
type: 'directory',
children: [{
_id: 6,
name: 'image.jpg',
type: 'file'
},
{
_id: 7,
name: 'image2.jpg',
type: 'file'
}]
}]
}]
}]
What I want to do is based on the _id value, get a path to that object using the name value.
So for example, for _id: 6 the path would be images/set 3/
I have a fiddle http://jsfiddle.net/6Lwrsjou/2/ for what I've tried, but this doesn't work, it includes previous sets that are not parents.
var path = '';
function getDirectory(objects, id) {
_.each(objects, function(item) {
if (item._id == id) return false;
if (item.type === 'directory') {
if (path.length > 1) {
path += '/' + item.name;
} else {
path += item.name;
}
};
if (!_.isEmpty(item.children)) {
getDirectory(item.children, id);
}
});
}
getDirectory(objects, 7);
console.log(path);
Any ideas?
You need a little change your code, for find in all objects, something like this
var objects = [{
_id: 1,
name: 'images',
type: 'directory',
children: [{
_id: 2,
name: 'set 2',
type: 'directory',
children: [{
_id: 3,
name: 'image.jpg',
type: 'file'
},
{
_id: 4,
name: 'image2.jpg',
type: 'file'
},
{
_id: 5,
name: 'set 3',
type: 'directory',
children: [{
_id: 6,
name: 'image.jpg',
type: 'file'
},
{
_id: 7,
name: 'image2.jpg',
type: 'file'
}]
}]
}]
},{
_id: '1a',
name: 'images2',
type: 'directory',
children: [{
_id: '2a',
name: 'image2.jpg',
type: 'file'
}]
}]
function gd(arr, id, p){
var i,len,j, childlen;
console.log('gd:'+p);
for(i=0, len=arr.length; i<len;i++){
if(arr[i]._id == id) return p+'/'+ arr[i].name;
if(arr[i].children && arr[i].children.length >0){
var f = gd(arr[i].children,id,p+'/'+arr[i].name)
if(f) return f;
}
}
}
document.getElementById('result').innerHTML = gd(objects, '2a','');
<span id="result"></span>
var objects = [{
_id: 1,
name: 'images',
type: 'directory',
children: [{
_id: 2,
name: 'set 2',
type: 'directory',
children: [{
_id: 3,
name: 'image.jpg',
type: 'file'
},
{
_id: 4,
name: 'image2.jpg',
type: 'file'
},
{
_id: 5,
name: 'set 3',
type: 'directory',
children: [{
_id: 6,
name: 'image.jpg',
type: 'file'
},
{
_id: 7,
name: 'image2.jpg',
type: 'file'
}]
}]
}]
},{
_id: '1a',
name: 'images2',
type: 'directory',
children: [{
_id: '2a',
name: 'image2.jpg',
type: 'file'
}]
}]
function getDirectory(object, id){
var path="";
for(var i=0; i<object.length; i++){
if(object[i]._id == id) return object[i].name;
else{
if(typeof(object[i].children) !== "undefined"){
temp = getDirectory(object[i].children, id);
if(temp){
path += object[i].name+"/" + getDirectory(object[i].children, id);
return path;
}
}
}
}
return false;
}
path = getDirectory(objects, "6");
console.log(path);

Deleting an object from an array using remove

Given:
var object = {key: value, key1: value, key2: value}
var array = [{object}, {object1}, {object2}, {object3}]
I want to use the parse javascript SDK to delete object 3 and 4 from the array. Using their key2 values. How do I do this?
I believe it goes something like:
object.remove("the key", [object2value2, object3value2])
I need more detail on how to articulate the key and the value. I looked at the docs and I just can't figure it out. I've spent days on this. Humor me, please I'm a newbie and I'm suffering!
THIS IS WHAT SHOWS IN MY TERMINAL AFTER MY PARSE QUERIES WHEN I LIST.GET("OBJECT");
I'd like to delete objects by _id. At the very bottom you see 'false' where I do LIST.REMOVE("_id", [array of _ids]):
[ { _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: 'QllVljV252iNZej9VQgBCYkEyD4Do9fvZMAvmK',
amount: 2307.15,
category: [ 'Shops', 'Computers and Electronics' ],
category_id: '19013000',
date: '2014-06-23',
meta: { location: [Object] },
name: 'Apple Store',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'NQQVQJVDgDhj90JvnXkMt1jm06eqzji5JvO52Z',
amount: 3.19,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-06-21',
meta: { location: [Object] },
name: 'Gregorys Coffee',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'Jwwrw1rnjnfXPvmG9KlZtDoXbQnW1VIMvwrMKp',
amount: 80,
category: [ 'Transfer', 'Withdrawal', 'ATM' ],
category_id: '21012002',
date: '2014-06-08',
meta: { location: [Object] },
name: 'ATM Withdrawal',
pending: false,
score: { location: [Object], name: 1 },
type: { primary: 'special' } },
{ _account: 'mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz',
_id: 'aWWVW4VqGqIdaP495pmetGRqAVKrLRFMD5bMrX',
amount: -240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-06-02',
meta: { location: {} },
name: 'Online Transfer from Chk ...1702',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'ZnnVnDVbybCqG4DV1BMgCPyAgyDz9vSA2Y5AG1',
amount: 240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-06-01',
meta: { location: {} },
name: 'Online Transfer to Sav ...9606',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'WOOVOlVrqrHaVDlAdGPmUAKg5k4qBafkZjRkb2',
amount: -0.93,
category: [ 'Interest' ],
category_id: '15000000',
date: '2014-05-17',
meta: { location: {} },
name: 'Interest Payment',
pending: false,
score: { location: {}, name: 0.2 },
type: { primary: 'unresolved' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '600r0LrVvViXjq96lBpdtyOWboBvzmsaZoeaVz',
amount: 12.74,
date: '2014-05-12',
meta: { location: [Object] },
name: 'Golden Crepes',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'pQQJQ9J0k0hqAVbDwMmYCrajm2JE6OUNBvwNYa',
amount: 7.23,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-05-09',
meta: { location: [Object] },
name: 'Krankies Coffee',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '2DD4Dl4nJnCPn4YRJK95hvwgWda5y2SWdDkW6m',
amount: 118.23,
category: [ 'Shops', 'Digital Purchase' ],
category_id: '19019000',
date: '2014-04-26',
meta: { location: {} },
name: 'Banana Republic',
pending: false,
score: { location: {}, name: 0.2 },
type: { primary: 'digital' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'oGGNG1NwYwUZQGOB5yjlhYMKG6yMQGtaON9aLd',
amount: -800,
category: [ 'Transfer', 'Third Party', 'Venmo' ],
category_id: '21010001',
date: '2014-04-20',
meta: { location: {} },
name: 'Venmo Cashout 18375552',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'pQQJQ9J0k0hqAVbDwMmYCrapBJba4BSNBvwNYk',
amount: 120,
category: [ 'Transfer', 'Third Party', 'Venmo' ],
category_id: '21010001',
date: '2014-04-19',
meta: { location: {} },
name: 'Venmo Payment 16991172',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '055z5gzVyVfzlBnEOqYvcoLL1ZgOWJhkrWMkv2',
amount: 5.32,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-04-17',
meta: { location: [Object] },
name: 'Octane Coffee Bar and Lounge',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: 'LvvrvyrOGOS2e5yE0Bdki45Y1ndVlgfoZ2zoOp',
amount: 28.57,
category: [ 'Food and Drink', 'Restaurants', 'Pizza' ],
category_id: '13005012',
date: '2014-04-11',
meta: { location: [Object] },
name: 'Papa Johns Pizza',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz',
_id: 'rEEwENwnznCQvkm61wRziKlMRPqaYztnR4vn61',
amount: -3042.44,
category: [ 'Transfer', 'Payroll' ],
category_id: '21009000',
date: '2014-03-27',
meta: { location: {} },
name: 'Company Payroll',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj',
_id: '944r40rPgPU2nXqzMYolS5nyo6Eo9OuqrlDkB',
amount: 200,
category: [ 'Transfer', 'Withdrawal', 'ATM' ],
category_id: '21012002',
date: '2014-07-21',
meta: { location: [Object] },
name: 'ATM Withdrawal',
pending: false,
score: { location: [Object], name: 1 },
type: { primary: 'special' } },
{ _account: 'AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj',
_id: 'rEEwENwnznCQvkm61wZ9uey62Pjy5YTqgYGDK',
amount: 240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-07-24',
meta: { location: {} },
name: 'Online Transfer from External Sav ...3092',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } } ]
false
The operand to remove needs to equal the object being removed. So first find the object you wish to remove...
var array = myObject.get("theArrayCol");
var removeMe;
for (var i=0; i < array.length; i++) {
if (array[i].key2 == "this one should be removed")
removeMe = array[i];
}
then remove it...
myObject.remove("theArrayCol", removeMe);
EDIT - based on our chat, here's how to apply this in your situation. I broke the code up into simpler functions, each doing an easily definable operation. I hope it makes it easier to understand, and I think its good programming practice anyway...
// token is your key to search the Transaction table in parse
function transactionWithToken(token) {
var query = new Parse.Query("Transactions");
query.equalTo("access_token", token);
query.select("transactions");
return query.first();
}
// array is the value of the array column on the Transaction table
// transactionId is a string that might match the value of the _id property in the array of objects
function transactionInArrayWithId(array, transactionId) {
for (var i=0; i<array.length; i++) {
if (array[i]._id == transactionId) return array[i];
}
return undefined;
}
function removeTransactionWithId(transaction, transactionId) {
var array = transaction.get("transactions");
var t = transactionInArrayWithId(array, transactionId);
transaction.remove("transactions", t);
}
// token is the key to the Transaction table
// transactionIds is an array of ids to remove from the Transaction object's transactions array
function removeTransactionsWithIdsFromToken(token, transactionIds) {
return transactionWithToken(token).then(function(result) {
for (var i=0; i<transactionIds.length; i++) {
removeTransactionWithId(result, transactionIds[i]);
}
return result.save();
});
}
This would be easier to understand if the column name and the table name weren't so similar. Also, underscorejs is great at this sort of array management.
you can try to filter it.
For example if you want to remove all objects which key 'k3' has value of 3;
var obj1 = {k1: 1, k2: 2, k3: 3};
var obj2 = {k1: 4, k2: 5, k3: 6};
var obj3 = {k1: 7, k2: 8, k3: 9};
var array = [obj1, obj2, obj3];
var badValue = 3;
var result = array.filter(function(obj){
return obj.k3 !== badValue;
});

Categories

Resources