AngularJS : How to concat two arrays? - javascript

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.

Related

How can I extract and pair the values of an array based object

I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)

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

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
})
)]

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')}/>

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Categories

Resources