How to Push Value to an Array Inside an Object - javascript

I have an array inside an Object which looks like this.
sourceSystemArray = [{
"attId" : 2257,
"attributeName" : "country",
"attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]
Using input field I give user option to add a new Value.
Now I would like to finally add the New Input value that I get using ngModel to attributeValues array.
So suppose user enters a new Country say NZ.
So I want to push NZ to attributeValues and my final Object should like this:
sourceSystemArray = [{
"attId" : 2257,
"attributeName" : "country",
"attributeValues" : [ "AU", "KG", "IN", "AF","NZ" ]
}]
I tried using push method but it's not working.
Can someone help me figure out how to achieve it.

If you're trying to add this object you might be having problems because it's in an array itself. Here's how I would add to attributeValues.
let myarray = [{
"attId" : 2257,
"attributeName" : "country",
"attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]
myarray[0].attribute values.push('GB')
Or, assuming it's not the only item in the array.
let myarray = [{
"attId" : 2257,
"attributeName" : "country",
"attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]
myarray.find(item => item.attId === 2257)
.attributeValues.push('GB')

Since sourceSystemArray is an array, try this
sourceSystemArra[0].attributeValues.push("NZ");

in html part u should send both attId and your new value with function
then in component u should find method with attId
function(attId,newValue){
this.sourceSystemArray.find(data=>data.attId ==attId).attributeValues.push(newValue);
}

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

React bootstrap table 2 programmatically select filter

I'm trying to follow this example. I've pretty much replicated it line for line, adding in 5 products as that data isn't given in the example. Everything displays correctly so in theory I've set it up correctly, however the filter doesn't seem to work like it does in the example.
Any ideas? This is what I have:
https://stackblitz.com/edit/react-mmvhyv?file=Table.js
Issue is with products data quality field and selectOption fields , they are is matched
It tries to compare the products data quality with selectOption's key
So either you change products
const products = [
{"id": "1", "name":"john", "quality":"unknown"},
{"id": "2", "name":"jane", "quality":"good"},
{"id": "3", "name":"bob", "quality":"Bad"},
{"id": "4", "name":"ralph", "quality":"Bad"},
]
To :
const products = [
{"id": "1", "name":"john", "quality":2},
{"id": "2", "name":"jane", "quality":0},
{"id": "3", "name":"bob", "quality":1},
{"id": "4", "name":"ralph", "quality":1},
]
WORKING DEMO
OR
change selectOptions to :
const selectOptions = {
'good' : 'good',
'Bad' : 'Bad',
'unknown' : 'unknown',
};
const handleClick = () => {
qualityFilter('good'); // <---- here to
};
WORKING DEMO
In case you are calling API and populating your table, you need to check the response data and map it with the text displayed on UI.
For eg:
{
"ID": 1,
"CreatedAt": "2021-09-02T04:30:45.37+05:30",
"UpdatedAt": "2021-09-02T04:30:45.37+05:30",
"DeletedAt": null,
"Gender":"male",
"roll_no": 1,
"first_name": "Ravi",
"use_transport": false
}
Suppose we want to add select filter on use_transport and Gender.
Observe that use_transport is boolean as false and Gender is string "male" not capitalized. On UI if you are representing this two field as
use_transport="false" and Gender="Male". Then you need to create options map as follows,
const genderSelectOptions = {
"male": "Male",
"female": "Female",
"other": "Other"
};
const booleanSelectOptions = {
true:"true",
false: "false"
}
The key will be the value coming in response and the value of the map will be the value you are representing on the UI.
NOTE: It is important to have one unique ID in your table, you can keep it hidden. Filter uses that ID internally to distinguish the unique record.
The unique key has to be then bind as keyField in Bootstrap table tag
<BootstrapTable
striped hover condensed pagination={true}
search
keyField='ID'
data={this.state.students}
columns={this.state.columns}
filter={filterFactory()}
pagination={paginationFactory()} />

JSON Objects in a JSON Array in javascript

I am playing around with JSON objects in JSON arrays. On click of a button, I push the json objects into a array like below:
jsonArray.push({
columnNameProperty: columnName,
columnValueProerty: columnValue,
id: column.id
});
My resulted array looks like this:
[
0:{
columnNameProperty: "Name",
columnValueProperty: "Nancy",
id: "123"
},
1:{
columnNameProperty: "Name",
columnValueProperty: "Jene",
id: "124"
},
2:{
columnNameProperty: "Amount",
columnValueProperty: "1000",
id: "123"
},
3:{
columnNameProperty: "State",
columnValueProperty: "WA",
id: "123"
}
]
How do I modify this as I want to push items based on the id.
[
"123" : {
"Name" : "Nancy",
"Amount" : "1000",
"State" : "WA"
},
"124" : {
"Name" : "Jene"
}
]
Anyone could suggest me how to structure it in this format.
#Amy is correct, that is not in fact valid javascript. Arrays do not have keys. So your example
[
0:{
columnNameProperty: "Name",
columnValueProperty: "Nancy",
id: "123"
},
1:{
columnNameProperty: "Name",
columnValueProperty: "Jene",
id: "124"
}
]
really looks like this
[
{
columnNameProperty: "Name",
columnValueProperty: "Nancy",
id: "123"
},
{
columnNameProperty: "Name",
columnValueProperty: "Jene",
id: "124"
}
]
If your goal is to retrieve an element by id you could make a function that loops through the array, finds and returns the object with the given id.
Alternatively, you could create a hash map and access each values by its key. So for instance, given this object:
let map = {
"123" : {
"Name" : "Nancy",
"Amount" : "1000",
"State" : "WA"
},
"124" : {
"Name" : "Jene"
}
}
You could get the value of the key "123" by saying map['123']
Why do you have to use an array? For what you are trying to achieve you can set up a object and then just insert more objects into it.
var exampleObject={};
function onClick(){
exampleObject["123"]={"Name":"steve"}
}
I assume you are trying to use that approach to later find the right object in the array?
You can simply loop over the object and find it in there:
for (var obj in exampleObject){
if(obj==="123"){
//do something
}
}
Was able to achieve the required format by creating HashMap/Object:
var id = column.id;
var mapObject = {}, editMap = {};
if(editMap.hasOwnProperty(id)){
mapObject = editMap[id];
mapObject[columnName] = grid[columnName];
editMap[id] = mapObject;
}
else{
mapObject[columnName] = [columnName];
editMap[id] = mapObject;
}

Fetch data from a nested array

I would like to know if there is a way to get the length from a nested array.
My data is a JSON file like this:
{
"data" :[
"item1" :'',
"item2" :[{
"id" :1,
"text":'text'
},{
"id" :2,
"text" : 'text
}]
]
}
I'm using angular 6 and ngx-restangular.
Is possible to get the item 2 length?
The main problem is the question does not provide a valid json. A valid json for the same would be like as under :
{
"data": {
"item1": "",
"item2": [{
"id": 1,
"text": "text"
},
{
"id": 2,
"text": "text"
}
]
}
}
Now you can fetch the second element size simply by
data["item2"].length
or
data.item2.length
To extend the Answer from #AurA
If you had to work with a valid array:
[
[ "item0.0", "item0.1" ],
[ "item1.0", "item1.1" ]
]
you could access the length of the nested arrays like this:
let a = [
["item0.0", "item0.1"],
["item1.0", "item1.1"]
];
let lengthA0 = a[0].length;
let lengthA1 = a[1].length;
console.log("length of a0: ", lengthA0);
console.log("length of a1: ", lengthA1);

access to json multidimensional array with react

I'm trying to access a certain element of my JSON, through React JS i use: Object.keys(field)[0] on the json and I get "punteggio" but I would like to get its value instead, for example "7". How can I access to this data?
"honours": [
{
"punteggio" : 7,
"serie" : "Serie A",
"tipo" : "icon-scudetto",
"anni" : "1926/1927 revocato, 1027/1928, 1942/1943, 1945/1946, 1947/1948"
},
{
"punteggio" : 4,
"serie" : "Serie B",
"tipo" : "icon-scudetto",
"anni" : "1958/1960, 1989/1990, 2000/2001, 2011/2012"
},
{
"punteggio" : 5,
"serie" : "Serie B",
"tipo" : "icon-coppaitalia",
"anni" : "1958/1960, 1989/1990, 2000/2001, 2011/2012"
}
]
"punteggio" - is just a key, so you can access its value like this
const key = Object.keys(field)[0];
const value = field[key];
Object.Keys used when you need to fetch key of array from the object
use Object.Values to fetch the value
Read more at :
https://javascript.info/keys-values-entries

Categories

Resources