Can't push array item to array data property - Vue Js - javascript

I a getting data from the laravel using this response :
$unserialize = unserialize($import->field_names);
return response()->json( $unserialize, 200 ) ;
Now on the Vue JS I can console the response using this :
console.log(response);
and It's showing the data in array (Check the red arrow mark):
Now, I have a options empty array property like this:
options : []
I want to push object data to this array with a key value and text. This key's value will be that response data single item. So, To do this, I am using this:
response.data.forEach((item, index) => {
this.options.push({
value: item,
text: index
});
});
but If I console
console.log(this.options);
I can not see the array of object to this options propery. I can see this:
can you tell me why? I want this options should store the item like this:
options: [
{ value: null, text: 'Please select some item' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Default Selected Option' },
{ value: 'c', text: 'This is another option' },
{ value: 'd', text: 'This one is disabled', disabled: true },
]
Update:
Console.log(response);

I think that the problem could be in this keyword
you can modify your code in this way
this.options = [...this.options,
...response.data.map((item, index) =>
({
value: item,
text: index
})
)]

Related

Return true if an array within an array contains specific key

I have the following the object:
items: [
{
object_a {
id: "1",
value: "somevalue1"
}
},
{
object_b {
id: "2"
value: "somevalue2"
items:[
{
nested_object_a {
id: "3"
value: "somevalue3"
},
nested_object_b {
id: "4"
value: "somevalue4"
},
}
]
}
},
]
I can check if the value key exists in the initial items array:
items.some(item => item.hasOwnProperty("value"));
To see if the value key exists in the nested object_b item array I can do the following:
items[1].object_b.items.some(item => item.hasOwnProperty("value"));
Instead of specifying which number in the array to look in I need to make the final expression dynamic. I'm certain I need to do a find or a filter on the top level items, but I've had no luck with it so far.
I found that using an every function on the items allowed me to return the boolean value I required form the array. The problem this created is any array item that didn't have the object_b key on was returning null and breaking my app. It turns out I needed to use an optional chaining operator to get around this (.?).
Thanks to #ikhvjs for linking that stackedoverflow article.
Working code:
items.every(item => {
item.object_b?.items.some(item => item.hasOwnProperty("value"));
});

Access object child property without using parent

I am using the html2json which gives me back an object with child objects. Like the code below. I want to get the value of the key text. But it differs per case how many child objects there are and thus where the key text is situated.
The code I have tried but for this reason, did not work every time was this one:
json.child[0].child[0].child[0].child[0].text
And this is an example of an object:
node: 'root', child: [
{
node: 'element',
tag: 'div',
attr: { id: '1', class: 'foo' },
child: [
{
node: 'element',
tag: 'h2',
child: [
{ node: 'text', text: 'sample text with ' },
{ node: 'element', tag: 'code', child: [{ node: 'text', text: 'inline tag' }] }
]
}
]
} ]
Is there another way to access this element? I was thinking of searching for a key in the object because the key "text" only occurs once. But do not know how this would work.
All help is really appreciated!
You could create a recursive function that will return an array of all the values where the key matches.
const data = {"node":"root","child":[{"node":"element","tag":"div","attr":{"id":"1","class":"foo"},"child":[{"node":"element","tag":"h2","child":[{"node":"text","text":"sample text with "},{"node":"element","tag":"code","child":[{"node":"text","text":"inline tag"}]}]}]}]}
function findByKey(data, key) {
const result = [];
for (let i in data) {
if (i === key) result.push(data[i]);
if (typeof data[i] === 'object') {
result.push(...findByKey(data[i], key))
}
}
return result;
}
console.log(findByKey(data, 'text'))

How to search within the nested array of objects in javascript?

i want to search a for a string say for example "hello" within 'name' in array of objects. The data structure is like the one below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
{name: 'new', value: 'value5'}];
So from the above mentioned data structure, if the search query is say 'hello' i want to check through 'name' field of each object. also check within children 'name' field of each object. Some object may or may not have children and nested children too. I want to retreive the objects that have matched the search query.
For example if my search query is 'hello' then the expected output is as below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
i have tried using the below search method but that doesnot search within children and nested children.
search = (query, listitems => {
if (!query) {
return listitems;
}
query = query.toLowerCase();
const results = [];
let counter;
let childcounter;
listitem.forEach((listitem) => {
counter = 0;
childcounter = 0;
if (listitem['name'].toLowerCase().indexOf(query) > -1)
{
counter++;
if (listitem.children)
{
listitem.children.forEach ((child) => {
if (child['name'].toLowerCase().indexOf(query) > -1)
childcounter++;
});
}
listitem.counter = counter;
listitem.childcounter = childcounter;
results.push(listitem);
}
return result
});
How can i do it. could someone help me with it. Thanks.

Distinct Values using Set

I have been using
<FormGroup>
<Campaign
campaignName={this.campaignName.bind(this)}
campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
</FormGroup>
to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.
I have refactored the code as follows,
<FormGroup>
<Campaign
campaignName={this.campaignName.bind(this)}
campaignOptions={[...new Set(this.props.records.map(options => {
return {value: options.campaign, label: options.campaign };
}))]}/>
</FormGroup>
...but the unique element is now not working (see below with duplicates). What am I doing wrong please?
The input array looks like...
[
1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
… more in here including more than 1 object with instagram launch for example
]
Original approach resulted in Array of...
0:"newevent"
1:"sheffieldevent"
2:"stuffinhere"
3:”instagramlaunch"
4:”anothertest"
5:”yetanother"
now results in...
0:{value: "newevent", label: "newevent"}
1:{value: "sheffieldevent", label: "sheffieldevent"}
2:{value: "stuffinhere", label: "stuffinhere"}
3:{value: "instagramlaunch", label: "instagramlaunch"}
4:{value: "instagramlaunch", label: "instagramlaunch"}
5:{value: "instagramlaunch", label: "instagramlaunch”}
6:{value: "anothertest", label: "anothertest”}
7:{value: "yetanother", label: "yetanother"}
new Set(this.props.records.map(options => {
return {value: options.campaign, label: options.campaign };
}))
Does not work, because every new object is a unique object and Set works with all types. As result, you get all options, but not unique options.
If you have the same pattern as you want, you could render the set after collecting all values and build a new objects array out of the set.
var optionsSet = new Set(array.map(option => option.campaign)),
options = Array.from(optionsSet, v => ({ value: v, label: v }));
I resolved this using lodash...
campaignOptions={_.uniqBy(this.props.records.map((options,index) => {return { value: index, label: options.campaign }}),'label')}/>

AngularJS : How to concat two arrays?

I have following arrays with values (i am generating the values on go)
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
I want to concatenate these two objects to get the following result
[{Name:''},{ Key: '', Value: '' }]
Plunker link , somehow that's not working either
when I click on the add row button it will add another row for key and value text boxes only not for name, I can add n no of rows and when I click on Submit it should show the kev value pair as
[{Name:''},{ Key: '', Value: '' },{ Key: '', Value: '' },{ Key: '', Value: '' }.....so on]
Thanks
Not sure why you want to build an array of mismatched objects. That seems to me to be asking for trouble. I would suggest possibly doing the following:
$scope.objects = [{Name: '', Elements: []}];
Then you can easily manage multiple objects who have elements:
(I use underscore http://underscorejs.org/)
$scope.addElementToObject = function(objName, element){
_.where($scope.mergedArray, {Name: objName}).Elements.push(element);
};
Then you can add to the list of elements for that object without having to eval the object in the elements array on each use.
If you still want/need to merge arrays of mismatched objects, it would be the following:
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
$scope.mergedArray = $scope.objectName.contact($scope.propertiesElement);
$scope.addElement = function(element){
$scope.mergedArray.push(element);
};
Then, in your click event code:
$scope.addElement({ Key: 'someKey', Value: 'Some Value' });
I hope this helps.

Categories

Resources