I've this json return
data = [
{ firstName: "Christophe",
lastName: "Coenraets"},
{ firstName: "John",
lastName: "Smith"}
];
I want to display each object in a li list and want to use Enumerable condition. I understand if it'd been like
data = { elem :[
{ firstName: "Christophe",
lastName: "Coenraets"},
{ firstName: "John",
lastName: "Smith"}
]};
I can use something like
{{#elem}}
<li>{{firstName}} {{lastName}}</li>
{{/elem}}
But in the first case, how do I check the condition?
I don't work with icanhaz, it very well may have a method to parse the data that you get, but you could always modify the JSON object and wrap it into a parent element like in your second case:
myData = { elem : data};
Related
I have array of objects like this:
var array = [
{
name: "John",
surname: "Doe",
title: "mister"
},
{
name: "Jane",
surname: "Smith",
title: "miss"
},
{
name: "Doe",
surname: "Mustermann",
title: "mister"
}
]
I want to implement a search term through this that will look through multiple properties while sorting them with property priority.
Example: If search term would be Doe, I would like to get this output:
[
{
name: "Doe",
surname: "Mustermann",
title: "mister"
},
{
name: "John",
surname: "Doe",
title: "mister"
}
]
name property has higher priority than surname, that's why hit on name object would go on top.
Filter function only filters through array, but I also would need to move objects up based if search term hit specific field that has higher priority.
I tried implementing this with combination of filter and sort, but unfortunately this was a failure due to both searching through multiple fields in objects, with moving some objects on top depending on which property search was found.
Have a list of fields, ordered by priority:
let fields = ['name', 'surname', 'title']
and then compute the result like this:
let result = fields.flatMap(f => array.filter(x => x[f] === search))
I have read several solutions to this problem here. When I try it, I continue to receive an error for the pop() method.
I have what is essentially a multidimensional array in javascript.
I am tasked with returning the array with the sensitive info removed (e.g. remove the SSN, in this example)
I thought I could use a foreach loop, and the pop() function to remove the last element of the child arrays, the SSN.
testing it using node on the commandline, the stdout is telling me that element.pop() is not a function. i've tried it with pop(), slice(), filter(), all with no success.
when running $> node filename.js
H:\Apache2\htdocs\test\filename.js:50
noppi[i] = element.pop();
^
TypeError: element.pop is not a function
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
let i = 0;
let noppi = [];
recs.forEach(element => {
noppi[i] = element.pop();
i++;
});
console.log(noppi);
At the risk of sounding redundant, I'll briefly reiterate what the earlier answers have already stated.
The input data structure isn't a multi-dimensional array [ [ ... ], [ ... ] ] , it's an array of objects [ {...}, {...} ]. So you can't use Array methods like .pop() on the objects {...}.
Here's a simple one-liner that uses .forEach() and delete.
recs.forEach(obj => delete obj.SSN)
delete is an operator with one purpose: to remove an object's property like for example SSN: '123-45-6789'. Simple and perfect.
Note, .forEach() mutates the array, meaning that it's the original data being changed (see Minja's comment).
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
recs.forEach(obj => delete obj.SSN);
console.log(recs)
Try this:
recs.forEach(element => {
noppi.push = element;
});
You are trying to use pop() on an object not an array
As per your need you need to remove SSN from your object, try below code it should work for you.
recs.forEach(element => {
const { SSN, ...rest } = element;
noppi.push(rest);
});
Here we are removing SSN from object and rest will push in noppi.
I was just wondering is it possible to remove extra unknown properties from object.
The exact problem which I am facing is that I know what fields I need in object, but I don't know what extra is coming and I need to remove those extras.
One option which comes in my mind is using hasOwnProperty function since we know what all properties we need.
Ex : Suppose we are getting below object :
{
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
}
Now, we know that we need name, age, address and city in address beforehand but we are getting prop1 also as extra here and we don't know that it is exactly. It could be anything. We need to remove this prop1 from this object. This is just an example.
I think we need to use some recursive approach because the extra property could be at any place in the object.
Note: We have a list of properties which we need in advance.
I defined a schema form of json (modify it as you want) and then I made a function that receives the json required to delete unwanted elements from it.
const needAttribute = {
name: "Harry",
age: 16,
gender: "Male",
Address: {
City: "LA"
}
}
var json =
{
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
}
function getNeedAttributeFromJson(Myjson){
for(var element in Myjson){
if(needAttribute.hasOwnProperty(element)){
if (typeof Myjson[element] === "object") {
for(var subElement in Myjson[element]){
if(!needAttribute[element].hasOwnProperty(subElement)){
delete Myjson[element][subElement];
}
}
}else{
continue;
}
}else{
delete Myjson[element];
}
}
return Myjson;
}
console.log(getNeedAttributeFromJson(json));
You can use lodash library.
REFERENCE URL - https://lodash.com/docs/4.17.15#omit
const object = {
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
object = _.omit(object.Address, 'prop1');
console.log(object);
I was wondering, if it's possible to ensure with Angular 12 / Typescript, that all objects within an array have the same properties, without declaring the properties explicitly (should be generic).
Here's an example of what I want to achieve:
// This should compile because all objects have the same properties
const correct = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
{firstname: 'Walter', lastname: 'Walker'}
]
// This shouldn't compile because some object have different properties
const wrong = [
{firstname: 'Aline', lastname: 'Rose', phone: 'xxx-xxx-xx-xx'},
{firstname: 'Daniel', email: 'dan#gmail.com'},
{firstname: 'Louisa', email: 'louisa#icloud.com'}
]
I was able to create an Interface which only allows properties with type string, but I couldn't achieve the example above.
export interface Data {
[keys: string]: string
}
Update (Use-Case)
I need this check in a service which exports data. You should be able to pass an array of objects, which represent rows within a table.
For example:
const data = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
]
this.exportService.export(data);
This code would generate a file with a table like this:
firstname
lastname
Jack
Sanders
Susanna
Marsaglia
The service should support any passed data, because it's used widely over our entire application. But to be sure that the service can export the data to a table, we need to ensure, that all passed objects have the same properties (e.g. columns).
function sameKeys(input) {
if (!input || input.length === 0) return;
const keys = new Set(Object.keys(input[0]));
return input.every((item) => Object.keys(item).every((key) => keys.has(key)));
}
If you want a compile time check, then doing a proper type definition makes sense have given in another answer. But that will only work if this data is hardcoded. if you are fetching it from backend it will not work as types are lost when the code is already build as javascript don't have types.
You can very well make your exportservice generic, ie something like this
class ExportService {
public export<T>(data: T[]) {
console.log(data);
}
}
Or you can also just use {[key:string]:string} as element type in you export service
class ExportService {
public export(data: {[key:string]:string}[]) {
console.log(data);
}
}
That doesn't hinder you from defining the type of your data correctly.
const data: { firstname: string, lastname: string}[] = [
{ firstname: "john", lastname: "foo"},
{ firstname: "jim", lastname: "bar"}
];
this.exportservice.export(data);
See also this fiddle
const data = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
{firstname: 'Walter', lastname: 'Walker'}
]
const dataReference : Required<typeof data[number]>[] = data
You should achieve this by interface as below
interface IStructure {
firstname: string;
lastname: string;
}
const correct: Array<IStructure> = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
{firstname: 'Walter', lastname: 'Walker'}
];
//wrong will throw error
I'm not sure if I phrased the question right. I'm fairly new to JavaScript, and I'd like to add multiple objects (?) to an array.
If I have this array:
let arr = [{
firstname: "John",
lastname: "Smith"
}];
How would I add, say
var firstname = "John";
var lastname = "Doe";
as
{ firstname: "John", lastname: "Doe" }
to the same array?
Items can be added to an array with the push method. Every array has this method build it, together with many other methods, and can be used to push a new value to the end of the array.
var arr = [
{
firstname: "John",
lastname: "Smith"
}
];
In the push method create an object with the keys and the values that you want to add.
var firstname = "John";
var lastname = "Doe";
arr.push({
firsName: firstName,
lastName: lastName
});
If the keys of the object are the same name as the variables then you can use the syntax below. This will give the object keys with the same name as the variable and set the value of the variable with it as the value of the key.
arr.push({ firstName, lastName });
Alternatively if you want to add an object to the beginning of the array, use the unshift method of the array.
arr.unshift({ firstName, lastName });
You can also do this with spread operator:
var arr = [{firstname: "John", lastname: "Smith"}];
arr= [...arr, {firstname: "Name1", lastname: "LName"}]
console.log(arr);
Take a look at push.
let arr = [{
firstname: "John",
lastname: "Smith"
}];
var firstname = "soham";
var lastname = "s";
arr.push({
firstname: firstname,
lastname: lastname
})
console.log(arr);