combine multiple list to single array - javascript

{ "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] } and this my script var body = request.body;for(var i = 0;i < body.data.length;i++){var obj = body.data[i];var keyes = Object.keys(obj);} the problem response from var keyes = Object.keys(obj); is list like this [ 'firstName' ] [ 'lastName' ] i'm wanna like this ['firstName', 'lastName']
Thanks before.

Assuming each of the arrays are elements of a parent array, one way you could achieve this is by using Array.prototype.reduce:
const flat = [
["aku"],
["dia"],
["ia"]
].reduce((accum, el) => accum.concat(el), [])
console.log(flat);

EDITED: You could concat each item of your array :
const body = {
"data": [
{"firstName": "Achmad"},
{"lastName": "a"}
]
};
let result = [];
for (item of body.data) {
result = result.concat(Object.keys(item));
}
console.log(result); // -> ['firstName', 'lastName']

Maybe you want to do something like this
var body = request.body;
var keyes = [];
for(var i = 0; i < body.data.length; i++){
var obj = body.data[i];
keyes.push( Object.keys(obj) );
}

Related

Trim Array value from specific char to specific char

How to get specific value from array?
i.e.
"Names": [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
Output must be:
"Names": [
"name",
"Type",
"Option",
"Pointer"
]
Try like this:
export class AppComponent {
Names = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
constructor() {
var modifiedNames = this.Names.map(x => x.split('[').pop().split(']')[0])
console.log(modifiedNames)
}
}
See Stackbiltz Demo
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
const newArray = array.map(e => /^\w+\[(\w+)\]$/.exec(e)[1]);
// ["name", "Type", "Option", "Pointer"]
You can use substring method and based on the start and end bracket grab the subtring. To iterate on every element of array use map function, it creates a new array with the results of calling a provided function on every element in the calling array.
const arr = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
let result = arr.map((a)=>{ return a.substring(a.indexOf("[") + 1 , a.indexOf("]")) });
console.log(result);
You can loop through array and using following regex to get the desired output.
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
var regexTest = new RegExp(/\[([^\]]+)\]/);
var newArray = array.map(e => regexTest.exec(e)[1]);
fiddle link
substring and indexOf in action:
let newArray = [];
for(var i=0; i<array.length; i++){
var s = array[i];
var n = s.indexOf('[');
s = s.substring(n+1, s.length-1);
newArray.push(s);
}
OR
let newArray = [];
for(var i=0; i<array.length; i++){
newArray.push(array[i].substring(array[i].indexOf('[')+1, array[i].length-1));
}

Array is null after assigning value to it

I have variable that is containing some sort of JSON data,
var blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
]
What I want a new array titleFilter like:
var titleFilter = [
Bangladesh : "/img/blog/bangladesh.jpg",
India : "/img/blog/india.jpg"
]
So, for this purpose, I have tried this:
var titleFilter = [];
for (var i = 0; i < blogData.length; i++) {
titleFilter[blogData[i].blogTitle] = blogData[i].imagePath;
}
The problem is, I am getting the titleFilter array as:
var titleFilter = [
Bangladesh : "",
India : ""
]
It would be great if someone help me regarding this problem.
Try this:
const blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
];
const result = blogData.reduce((acc, ele)=> (acc[ele.blogTitle] = ele.imagePath , acc),{});
console.log(result);
I am not sure what you are looking for but you can use map like this to achieve it.
var map = new Object(); // or var map = {};
map[blogData[i].blogTitle] = blogData[i].imagePath;
var blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},
{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
]
var titleFilter = {}
blogData.forEach( x => titleFilter[x.blogTitle] = x.imagePath )
Use this code, and you will get the desired result in titleFilter

Create dynamic object based on array element: Javascript [duplicate]

I have the following array:
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"];
I want to have the following output:
var desiredOutput = [{
"CONTAINER": [{
"BODY": [{
"NEWS": [{
"TITLE": []
}]
}]
}]
}];
How can I achieve this in JavaScript?
Already tried with recursive loop, but it does not work, gives me undefined.
dataChange(sampleArray);
function dataChange(data) {
for (var i = 0; i < data.length; i++) {
changeTheArray[data[i]] = data[i + 1];
data.splice(i, 1);
dataChange(changeTheArray[data[i]]);
}
}
Thanks
This does what you're asking for, in one line, and with no additional variables:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
The reduceRight call, starting from the right hand end of the array, progressively accumulates the current data (seeded with the initial value of []) as the value of the single key in a new object { [key] : _value_ } where that object is itself the single entry in an array [ ... ].
This will do it:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => { // For every entry, named `key` in `sampleArray`,
const next = []; // New array
current.push({[key]: next}); // Add `{key: []}` to the current array,
current = next; // Move the pointer to the array we just added.
});
console.log(data);
{[key]: next} is relatively new syntax. They're computed property names.
This:
const a = 'foo';
const b = {[a]: 'bar'};
Is similar to:
const a = 'foo';
const b = {};
b[a] = 'bar';
You could re-write the forEach as a one-liner:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => current.push({[key]: current = [] }));
console.log(data);
This current.push works a little counter-intuitively:
Construct a new element to push. This assigns a new value to current.
Push the new element to the reference .push was called on.
That reference is the value of current before current = [].
Hi i made a little demo :
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"
],
generateArray = [],
tmp = null;
for(var i = 0; i < sampleArray.length; i++) {
if(tmp===null){
generateArray[sampleArray[i]] = {};
tmp = generateArray[sampleArray[i]];
}else{
tmp[sampleArray[i]] = {};
tmp = tmp[sampleArray[i]];
}
}
console.log(generateArray);

Flat array to multi dimensional array (JavaScript)

I have the following array:
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"];
I want to have the following output:
var desiredOutput = [{
"CONTAINER": [{
"BODY": [{
"NEWS": [{
"TITLE": []
}]
}]
}]
}];
How can I achieve this in JavaScript?
Already tried with recursive loop, but it does not work, gives me undefined.
dataChange(sampleArray);
function dataChange(data) {
for (var i = 0; i < data.length; i++) {
changeTheArray[data[i]] = data[i + 1];
data.splice(i, 1);
dataChange(changeTheArray[data[i]]);
}
}
Thanks
This does what you're asking for, in one line, and with no additional variables:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
The reduceRight call, starting from the right hand end of the array, progressively accumulates the current data (seeded with the initial value of []) as the value of the single key in a new object { [key] : _value_ } where that object is itself the single entry in an array [ ... ].
This will do it:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => { // For every entry, named `key` in `sampleArray`,
const next = []; // New array
current.push({[key]: next}); // Add `{key: []}` to the current array,
current = next; // Move the pointer to the array we just added.
});
console.log(data);
{[key]: next} is relatively new syntax. They're computed property names.
This:
const a = 'foo';
const b = {[a]: 'bar'};
Is similar to:
const a = 'foo';
const b = {};
b[a] = 'bar';
You could re-write the forEach as a one-liner:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => current.push({[key]: current = [] }));
console.log(data);
This current.push works a little counter-intuitively:
Construct a new element to push. This assigns a new value to current.
Push the new element to the reference .push was called on.
That reference is the value of current before current = [].
Hi i made a little demo :
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"
],
generateArray = [],
tmp = null;
for(var i = 0; i < sampleArray.length; i++) {
if(tmp===null){
generateArray[sampleArray[i]] = {};
tmp = generateArray[sampleArray[i]];
}else{
tmp[sampleArray[i]] = {};
tmp = tmp[sampleArray[i]];
}
}
console.log(generateArray);

Javascript: convert JSON object to multiple arrays

I have an JSON object (hope so?):
[{"label":"label1","value":"value1"}
{"label":"label2","value":"value2"}
{"label":"label3","value":"value3"}]
I want to convert/extract that in 2 arrays like:
var labels = [label1,label2,label3]
var values = [value1,value2,value3]
I have no idea...
Assuming you would like two arrays and there is only ever two properties called label and value in each object, then this would be fine: -
var json_string = '[{"label":"label1", "value":"value1"}, {"label":"label2", "value":"value2"}, {"label":"label3", "value":"value3"}]';
var array = JSON.parse(json_string);
var labels = [];
var values = [];
for (var i = 0; i < array.length; i++) {
labels.push(array[i].label);
values.push(array[i].value);
}
Output: -
console.log(labels); // ["label1", "label2", "label3"]
console.log(values); // ["value1", "value2", "value3"]
You could use the map function to create your results:
var dataObj = [{"label":"label1","value":"value1"},
{"label":"label2","value":"value2"},
{"label":"label3","value":"value3"}];
var labels = dataObj.map(function(obj) {return obj.label;});
var values = dataObj.map(function(obj) {return obj.value;});
I think this solution is more elegant then manually iterating the array.
One other implementation could be;
var dataObj = [{"label":"label1","value":"value1"},
{"label":"label2","value":"value2"},
{"label":"label3","value":"value3"}],
dataStr = JSON.stringify(dataObj),
r = /label":"(\w+).+?value":"(\w+)/g,
m = [],
values = [],
labels = [];
while ((m = r.exec(dataStr)) !== null){
labels.push(m[1]);
values.push(m[2]);
}
console.log(labels, values); // [ 'label1', 'label2', 'label3' ] [ 'value1', 'value2', 'value3' ]
A proposal with one object as result with dynamic keys.
var array = [{ "label": "label1", "value": "value1" }, { "label": "label2", "value": "value2" }, { "label": "label3", "value": "value3" }],
result = {};
array.forEach(function (a) {
['label', 'value'].forEach(function (k) {
result[k] = result[k] || [];
result[k].push(a[k]);
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Categories

Resources