How to traverse push arrays if are not equal to values? - javascript

My requirements are very simple: iterate over the array, use the object to determine the selected object, and then push it into the new array, but I don't know how to write it?
Want the result as follows:
[{
key: 'name',
name: "A",
},
{
key: 'note',
name: "C”,
}
]
My code:
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = []
data[0].data.list.map(item => {
data[0].data.show.forEach(prop => {
if (prop !== item.key) {
arr.push({
key: item.key,
name: item.name
})
}
})
})
console.log(arr);

You could check the key if it is not includes in the show property and then push the object.
var data = [{ data: { list: [{ name: "A", key: "name" }, { name: "B", key: "title" }, { name: "C", key: "note" }, { name: "D", key: "desc" }], show: ["title", "desc"] } }],
arr = [];
data[0].data.list.map(({ key, name }) => {
if (!data[0].data.show.includes(key)) {
arr.push({ key, name });
}
});
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Try
let d=data[0].data;
let arr= d.list.filter(x=> !d.show.includes(x.key));
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
let d=data[0].data;
let arr= d.list.filter(x=> !d.show.includes(x.key));
console.log(arr);

var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = []
data[0].data.list.forEach(keyValue=> !data[0].data.show.includes(keyValue.key) ? arr.push(keyValue): null)
console.log(arr);

var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = data[0].data.list.filter(item => data[0].data.show.every(props => props !== item.key))
console.log(arr);

Related

Split array values into new array of keys/values

I have an array of objects like the following:
organisationData = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
]
I need to split this array so that it follow the following format:
organisations = [
{
"name": "Apple",
"field": "IT"
},
{
"name": "Microsoft",
"field": "IT"
}
]
I can create a new array that follows the correct format but each 'company' is part of the same array and I'd like to split them out, how do I modify the following?:
let organisationData = [.....]
let organisations = [];
for (org of organisationsData) {
_org = [];
_org[org.key] = org.value;
organisations.push(_org);
};
const organisationData = [
{
id: -516538792,
label: "name",
value: "Apple",
key: "name",
},
{
id: -586565959,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Microsoft",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Amazon",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Dell",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "Laptop Manufacturing",
key: "field",
},
];
let newOrgArray = [];
organisationData.map((m, index) => {
if (index % 2 === 0) {
let orgObj = { name: "", feild: "" };
orgObj["name"] = m.value;
orgObj["feild"] = organisationData[index + 1].value;
newOrgArray.push(orgObj);
}
});
console.log(newOrgArray);
Is this what you trying to achieve :
Data = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
];
result = []
for (var i = 0; i < Data.length; i+=2) {
Temp = {};
Temp[Data[i]['key']] = Data[i]['value'];
Temp[Data[i+1]['key']] = Data[i+1]['value'];
result.push(Temp)
}
console.log(result);
Output :
[ { name: 'Apple', field: 'IT' }, { name: 'Microsoft', field: 'IT' } ]
var organisationData = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
];
var organisation = [];
var i = 0;
var temp = '';
organisationData.forEach(function(org){
if(org.key == 'name'){
temp = org.value;
}
if(org.key == 'field'){
organisation[i] = {'name': temp, 'field': org.value};
i++;
}
});
console.log(organisation);

Creating a new array from the parents of array child element

I have the following array
{
"id": "111",
"name": "1111",
"children": [
{
"id": "22222",
"name": "2222",
"children": [
{
"id": "AAAA",
"name": "AAAA",
"children": [
{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [
{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [
{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}
]
}
And I would like to create an array with the parents of a child by its ID.
So for example if I wanted to get the path to the child with ID "FFF", then the array would look like something like this:
["1111", "2222", "BBB", "FFF"]
How could I go about doing that?
You could take an iterative and recursive approach.
function getItems({ children, ...object }, key, value) {
var temp;
if (object[key] === value) return [object];
if (children) children.some(o => temp = getItems(o, key, value));
return temp && [object, ...temp];
}
var data = { id: "111", name: "1111", children: [{ id: "22222", name: "2222", children: [{ id: "AAAA", name: "AAAA", children: [{ id: "DDD", name: "DDD" }, { id: "EEE", name: "EEE" }] }, { id: "BBBB", name: "BBB", children: [{ id: "FFF", name: "FFF" }, { id: "GGG", name: "GGG", children: [{ id: "7777", name: "7777" }, { id: "8888", name: "8888" }] }] }] }] };
console.log(getItems(data, 'id', 'FFF'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could implement a recursive search to find all paths and return the correct one when you reach the desired name-value pair.
const isObject = (obj) => obj === Object(obj);
let data = loadData();
let expected = [ '1111', '2222', 'BBB', 'FFF' ];
let actual = findPath(data, 'name', 'FFF');
console.log(JSON.stringify(expected) === JSON.stringify(actual));
function findPath(data, key, value, includeIndicies=false) {
let opts = { found : null, includeIndicies : includeIndicies };
findPathInternal(data, key, value, opts, []);
return opts.found;
}
function findPathInternal(node, key, val, opts, path) {
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i++) {
findPathInternal(node[i], key, val, opts, opts.includeIndicies ? path.concat(i) : path);
}
} else if (isObject(node)) {
if (node[key] === val) {
opts.found = path.concat(val); return; // Exit
} else {
let keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
findPathInternal(node[keys[i]], key, val, opts, path.concat(node[key]));
}
}
}
};
function loadData() {
return {
"id": "111",
"name": "1111",
"children": [{
"id": "22222",
"name": "2222",
"children": [{
"id": "AAAA",
"name": "AAAA",
"children": [{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

Dynamically create array of objects from the object with the array values

Currently I have the below object structure,
`let selectedOptions = {
"color": {
"id": "2",
"values": [
{
"value": "red",
"label": "Red",
"id": 1
},
{
"value": "blue",
"label": "Blue",
"id": 2
}
]
},
"size": {
"id": "19",
"values": [
{
"value": "medium",
"label": "Medium",
"id": 2
}
]
},
"demo": {
"id": "19",
"values": [
{
"value": "neylon",
"label": "Neylon",
"id": 2
}
]
}
.
.
.
N
}; `
And want to create array of objects from the above object like as below,
[
{ color: "red", size: "medium", demo: "neylon" },
{ color: "blue", size: "medium", demo: "neylon" }
]
I have tried like below but it didn't worked
https://jsfiddle.net/6Lvb12e5/18/
let cArr = [];
for(key in selectedOptions) {
selectedOptions[key].values.forEach(function(val,i) {
cArr.push({ [key]: val.value })
})
}
Thanks
You could take the wanted parts, like color, size and demo and build a cartesian product out of the given data.
const
cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
options = { color: { id: "2", values: [{ value: "red", label: "Red", id: 1 }, { value: "blue", label: "Blue", id: 2 }] }, size: { id: "19", values: [{ value: "small", label: "Small", id: 1 }, { value: "medium", label: "Medium", id: 2 }] }, demo: { id: "19", values: [{ value: "neylon", label: "Neylon", id: 2 }] } },
parts = Object
.entries(options)
.map(([k, { values }]) => [k, values.map(({ value }) => value)]),
keys = parts.map(([key]) => key),
result = parts
.map(([, values]) => values)
.reduce(cartesian)
.map(a => Object.assign(...a.map((v, i) => ({ [keys[i]]: v }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am not sure that is this the best way to do this, and even the data is missing but as a comment, it is quite big to post but can try:
let selectedOptions = {
"color": {
"id": "2",
"values": [
{
"value": "red",
"label": "Red",
"id": 1
},
{
"value": "blue",
"label": "Blue",
"id": 2
}
]
},
"size": {
"id": "19",
"values": [
{
"value": "medium",
"label": "Medium",
"id": 2
}
]
},
"demo": {
"id": "19",
"values": [
{
"value": "neylon",
"label": "Neylon",
"id": 2
}
]
}
};
let cArr = [];
var obj = {};
var glob;
for(key in selectedOptions) {
selectedOptions[key].values.forEach(function(val,i) {
obj[key] = val.value;
}
)
glob = obj;
}
cArr.push(glob);
console.log(cArr)

How to make recursively nested array in javascript?

Below is the json I have:
{
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
Here I have 2 characteristics object of "test" - A and B.These 2 objects may or may not have "comprisedOf" array. For Eg A has"comprisedOf" array whereas B has not. These comprisedOf array further may or may not have comprisedof objects array.
Now i have to make an array out of this which should be like the given below array:-
[
{
"name": "test",
"children": [
{
"name": "A",
"children": [
{
"name":"A1",
"children:: [
{
"name": "A1.1"
},
{
"name": "A1.2"
}
]
},
{
"name": "A2"
},
{
"name": "A3"
},
{
"name": "A4"
}
]
},
{
"name": "B"
}
]
}
]
How this array can be formed recursively out of the first array?
Thanks so much!!
EDIT:- Here's what I have tried:-
var makeChildrenAll = function(dataChar){
dataChar.forEach(function(char){
if(char.comprisedOf) {
makeChildrenAll(char.comprisedOf);
}
childrenData.push({
name: char.name,
description: char.description,
children: childrenData
});
});
};
makeChildrenAll(dataChar);
In order to be recursive you want the function to return and be able to assign that return to current object
Something like
function mapItems(arr){
// return new array
return arr.reduce((a,c)=>{
var newObj={name:c.name};
if(Array.isArray(c.comprisedOf)){
// use returned array of recursive function to assign to `children` property
newObj.children = mapItems(c.comprisedOf)
}
return a.concat(newObj)
},[])
}
console.log(mapItems(data.characteristics))
.as-console-wrapper { max-height: 100%!important;}
<script>
var data ={
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
</script>
You could take a different start array and use a destructuring for the wanted properties.
function mapItems(array) {
return array.map(({ name, comprisedOf }) =>
Object.assign({ name }, comprisedOf && { children: mapItems(comprisedOf) }));
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES5
function mapItems(array) {
return array.map(function (o) {
var r = { name: o.name };
if (o.comprisedOf) {
r.children = mapItems(o.comprisedOf);
}
return r;
});
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources