components: any = [
{
id: "17:12610",
name: "custom-component",
hasWarning: true,
selectableKey: 'id',
preview: 'thumbnailLink',
children: {
"17:12610": {
"name": "cc-1",
"type": "instance",
"children": {
"7:43": {
"name": "icon-slot",
"children": {},
"type": "div"
}
}
}
}
}
];
Object.keys(this.components[0].children).forEach((res) => {
console.log(res);
});
I am iterating like this but its only giving me the first ID.
I want to get each children ID & Name. Also I want to track the index so that I can make changes on particular index
I want the output like this:
id: 17:12610
name: cc-1
id: 7:43
name: icon-slot
let child = components[0].children;
while (child) {
const id = Object.keys(child)[0];
const name = child[id].name;
console.log('id: ' + id + ' name: ' + name);
child = child[id].children;
}
You are specifying components[0] before your forEach function. If you have multiple elements in your components array then you will need something like:
(this.components).forEach((root => {
(root.children).forEach((child) => {
console.log('id:' + child + ' name:' + child.name);
}
}
);
Also, looking at your array construction, you have created an array of objects, not an array of key value pairs and so they will not have a key associated with them. If you want keys associated with them, change your object {} to a nested array [].
You edited your question to add the desired output format. I edited my answer accordingly.
You can create a recursive function to achieve the solution. Something like this:
const component = [{"id":"17:12610","name":"custom-component","hasWarning":true,"selectableKey":"id","preview":"thumbnailLink","children":{"17:12610":{"name":"cc-1","type":"instance","children":{"7:43":{"name":"icon-slot","children":{},"type":"div"}}}}}];
const recursive = (arr, formedArr=[]) => arr.reduce((a,e)=>{
Object.entries(e.children || e).forEach(([id, {name, children}])=>{
a.push({id, name});
if(children) recursive([children], a);
});
return a;
},formedArr);
console.log(recursive(component));
Related
I have an array that is made from another array with the map method in JavaScript:
response = initialResponse.data.Resurs.map((item)=>({
KomRes:item.Kom,
levels:
[
...item.NumList.map((item)=>(
{
KomRes:item.Number,
})),
...item.SerList.map((item,index3)=>({
KomRes:"Serial: " + item.Ser,
})),
]}));
So, I have an array of 1 object and one array of objects. Now, I want to add indexes so that the parent object and all of its child objects have different indexes. One example would be:
[
{
KomRes:"abc"
id:1 // ==> Here the id is different to the levels objects id-s
levels:[{KomRes:"cde",id:2},{KomRes:"cdef",id:3}]
},
{
KomRes:"dfr"
id:4 // ==> Here the id is different to the levels objects id-s
levels:[{KomRes:"dsf",id:5},{KomRes:"sgsd",id:6}]
},
{
KomRes:"fgr"
id:7 // ==> Here the id is different to the levels objects id-s
levels:[{KomRes:"zizu",id:8},{KomRes:"hkl",id:9}]
},
]
As you can see, all of the objects have different ids (indexes). How can I achieve that?
I tried to add index to map method, but don't know how to achieve that with child map methods:
response = initialResponse.data.Resurs.map((item,index)=>({
KomRes:item.Kom,
id:index,
levels:
[
...item.NumList.map((item)=>(
{
KomRes:item.Number,
})),
...item.SerList.map((item,index3)=>({
KomRes:"Serial: " + item.Ser,
})),
]}));
Define a counter variable outside the function then on each iteration each object is given id property with an incremented value of the counter variable. Should there be any sub-arrays, they will be handled recursively by calling itself and passing in the sub-array.
const data=[{KomRes:"abc",id:null,levels:[{KomRes:"cde",id:null},{KomRes:"cdef",id:null}]},{KomRes:"ghi",id:null,levels:[{KomRes:"ijk",id:null},{KomRes:"ijkl",id:null}]},{KomRes:"mno",id:null,levels:[{KomRes:"omn",id:null},{KomRes:"omnp",id:null}]}];
let idx = 1;
function flatIndex(array) {
return array.map(obj => {
if (!obj.id) {
obj.id = idx++;
}
Object.values(obj).map(v => {
if (Array.isArray(v)) {
return flatIndex(v);
}
return obj;
});
return obj;
});
}
console.log(flatIndex(data));
Not sure if I understand well what you want to achieve, but you can declare a variable out of the scope and increment it along.
This gives the result you expect
const response = [
{ Kom: 'abc', NumList: [{ Number: "cde"}], SerList: [{ Ser: "cdef" }] },
{ Kom: 'dfr', NumList: [{ Number: "dsf"}], SerList: [{ Ser: "sgsd"}] },
{ Kom: 'fgr', NumList: [{ Number: "zizu"}], SerList: [{ Ser: "hkl"}] }
];
let lastId = 1; // index var to increment
const result = response.map((item) => ({
KomRes: item.Kom,
id: lastId++,
levels: [
...item.NumList.map((item) => ({
id: lastId++,
KomRes: item.Number,
})
),
...item.SerList.map((item) => ({
id: lastId++,
KomRes: "Serial: " + item.Ser,
})
),
]
})
);
console.log(result)
So I am pretty new when it comes to Javascript and it is as simple as read a json list with a value of:
{
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
What I would like to do is to have both the URL and the amount of numbers etc
"https://testing.com/en/p/-12332423/" and "999"
and I would like to for loop so it runs each "site" one by one so the first loop should be
"https://testing.com/en/p/-12332423/" and "999"
second loop should be:
"https://testing.com/en/p/-123456/" and "123"
and so on depending on whats inside the json basically.
So my question is how am I able to loop it so I can use those values for each loop?
As Adam Orlov pointed out in the coment, Object.entries() can be very useful here.
const URLobj = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
};
URLobj.URL.forEach(ob => {
console.log('ob', ob);
const entries = Object.entries(ob)[0]; // 0 just means the first key-value pair, but because each object has only one we can just use the first one
const url = entries[0];
const number = entries[1];
console.log('url', url);
console.log('number', number);
})
You mean something like this using Object.entries
const data = {
"URL": [
{"https://testing.com/en/p/-12332423/": "999"},
{"https://testing.com/en/p/-123456/": "123"},
{"https://testing.com/en/p/-456436346/": "422"}
]
}
data.URL.forEach(obj => { // loop
const [url, num] = Object.entries(obj)[0]; // grab the key and value from each entry - note the [0]
console.log("Url",url,"Number", num); // do something with them
})
let's call your object o1 for simplicity. So you can really go to town with this link - https://zellwk.com/blog/looping-through-js-objects/
or you can just use this code :
for(var i = 0; i < o1.URL.length; i++) {
//each entry
var site = Object.keys(URL[i]) [0];
var value = Object.values(URL[i]) [0];
// ... do whatever
}
don't forget each member of the array is an object (key : value) in its own right
You can extract the keys and their values into another object array using map
Then use the for loop on the newly created array. You can use this method on any object to separate their keys and values into another object array.
const data = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
var extracted = data.URL.map(e => ({
url: Object.keys(e)[0],
number: Object.values(e)[0]
}))
extracted.forEach((e) => console.log(e))
How can I make sure that no duplicates are displayed with vue inside a template ?
I my case the data is an array of objects and key that has a value of an object with multiple objects within it. So this would be a nested v-for in vue template syntax.
{
"matches": [
{
"birthday": "1/29/2019",
"household": {
"0": {
"relationship": "brother"
},
"1": {
"relationship": "brother"
}
}
}
]
}
I would only like to display 1 unique relationship per household. Please see fiddle for further examination https://jsfiddle.net/sxmhv3t7/
You can use computed property to make matches array unique.
For example:
computed: {
uniqueMatches () {
return this.matches.map(item => {
let households = Object.values(item.household)
let relationships = households.map(item => item.relationship)
const uniqueRelationships = [...new Set(relationships)]
item.household = uniqueRelationships.reduce((acc, cur, idx) => {
acc[idx] = {}
acc[idx].relationship = cur
return acc
}, {})
console.log(item)
return item
})
}
}
and then use uniqueMatches instead of matches in template
Demo in jsfiddle
You could massage the data a bit and create a uniqueHouseholdMembers array property on each match in the matches array and then just print out those values:
matches.forEach(match => {
let houseHolds = Object.values(match.household);
match.uniqueHouseholdMembers = houseHolds.reduce((acc, household) => {
// check if household member has already been added to our growing list
let isUniqueRelationship = !acc.includes(household.relationship);
// add household member if unique
if (isUniqueRelationship) {
acc.push(household.relationship);
}
return acc;
}, []);
});
// output using the data you provided:
// match[0].uniqueHouseholdMembers -> ['brother']
// match[1].uniqueHouseholdMembers -> ['sister']
// and if you have a 3rd match entry with more household members:
// match[2].uniqueHouseholdMembers -> ['brother', 'father', 'stranger']
I have attributes of objects of an array that I would like to store in an array. Below is my data.
What I want to do achieve is to store displays name attribute in opt[] so it would look like this opt = ['info1', 'info2', 'info3', ... ]
getEditData (id) {
axios.get('/api/campaign/getEdit/' + id)
.then(response =>{
this.campaign = response.data.campaign;
})
.catch(e=>{
console.log(e.data);
this.error = e.data
})
}
Above snippet is the source of the campaign object
You can use this expression:
campaigns.displays.map( ({name}) => name );
const campaigns = { displays: [{ name: 'info1'}, { name: 'info2'}] };
const result = campaigns.displays.map( ({name}) => name );
console.log(result);
This will display an array containing the property names of each object in the displays array
var data = {
displays: [
{
capacity: 9000,
id: 1,
imei: 44596
}
]
};
data.displays.forEach(function(obj, idx) {
console.log(Object.keys(obj));
});
Object.keys() is what you need
What is the best way to filter out data that exists within an object?
I was able to do use the below code when data was just an array of values but now I need to filter out any data where the item.QID exists in my array of objects.
Data Obj:
var data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob
}]
Snippet:
// I don't want to include data if this QID is in my object
this.employees = emp.filter(item =>!this.data.includes(item.QID));
From what I understand, includes only works on an array so I need to treat all of the QID values in my object as an array.
Desired Outcome: (assuming item.QID = ABC123)
this.employees = emp.filter(item =>!this.data.includes('ABC123'));
Result:
var data = [{
QID: 'DEF456',
Name: 'Bob'
}]
UPDATE:
Apologies, I left some things a little unclear trying to only include the necessary stuff.
// People Search
this.peopleSearchSub = this.typeahead
.distinctUntilChanged()
.debounceTime(200)
.switchMap(term => this._mapsService.loadEmployees(term))
.subscribe(emp => {
// Exclude all of the current owners
this.employees = emp.filter((item) => item.QID !== this.data.QID);
}, (err) => {
this.employees = [];
});
The above code is what I am working with. data is an object of users I want to exclude from my type-ahead results by filtering them out.
The question is a little ambiguous, but my understanding (correct me if I'm wrong), is that you want to remove all items from a list emp that have the same QID as any item in another list data?
If that's the case, try:
this.employees = emp.filter(item => !this.data.some(d => d.QID === item.QID))
some is an array method that returns true if it's callback is true for any of the arrays elements. So in this case, some(d => d.QID === item.QID) would be true if ANY of the elements of the list data have the same QID as item.
Try Object#hasOwnProperty()
this.employees = emp.filter(item =>item.hasOwnProperty('QID'));
You can use a for ... in to loop through and filter out what you want:
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
let newData = [];
let filterValue = 'ABC123';
for (let value in data) {
if (data[value].QID !== filterValue) {
newData.push(data[value]);
}
}
newData will be your new filtered array in this case
You can use an es6 .filter for that. I also added a couple of elements showing the filtered list and an input to allow changing of the filtered value. This list will update on the click of the button.
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
displayData(data);
function displayData(arr) {
let str = '';
document.getElementById('filterList').innerHTML = '';
arr.forEach((i) => { str += "<li>" + i.QID + ": " + i.Name + "</li>"})
document.getElementById('filterList').innerHTML = str;
}
function filterData() {
let filterValue = document.getElementById('filterInput').value;
filterText (filterValue);
}
function filterText (filterValue) {
let newArr = data.filter((n) => n.QID !== filterValue);
displayData(newArr)
}
<input id="filterInput" type="text" value="ABC123" />
<button type ="button" onclick="filterData()">Filter</button>
<hr/>
<ul id="filterList"><ul>