Converting array in to custom format - javascript

How can I convert the below array in to another format as specified below:
My array:
var test=[{"1":"Input"},{"2":"Output"}]
Converted array:
var result=
[
{
"id": "1",
"name": "Input"
},
{
"id": "2",
" name": "Output"
}
]
I tried with this code but not working.
var result = [];
for (var i = 0; i < test.length; i++) {
var newArray = {
id: Object.keys(test[i])[i],
name: test[i].name
}
result.push(newArray);
}

Inner array object doesn't have name property, so test[i].name will be undefined. You need to get the value using the key value. Also you can simplify your code using map() instead of for loop.
var test = [{
"1": "Input"
}, {
"2": "Output"
}];
var res = test.map(function(v) { // iterating over array object
var k = Object.keys(v)[0]; // getting object keys as an array & retrieving first key
return {
id: k, // setting id property as key
name: v[k] // and name property as value
}
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

You should use array.prototype.map for converting an array to another array using a conversion function.
array.prototype.map will iterate on all items and run a "conversion function" on each item.
Since your item is a key-value that looks like this: {"1":"Input"}, the only problem you have is that you don't know the key.
To get the keys of each object you can use the Object.keys method.
var test=[{"1":"Input"},{"2":"Output"}]; // input
var newArr = test.map(function(item){
var key = Object.keys(item)[0]; // get the object's keys and take the only key.
return {id: key, name: item[key]} // return the new object
});

Related

Dynamically create nested javascript objects with the same key but different values from an array

Need help figuring this out..
I want to create nested Javascript Object dynamically..
I have got a key, which has multiple values that needs to be nested per value in an array.
For example:
{
"name": [{
"desc": "A",
"age": 26,
"name": [{
"desc": "B",
"age": 12,
"name": [{
"desc": "C",
"age": 48
}]
}]
}]
}
So far i have this:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]
const name = "name"
var json = {};
var current = json;
for (var i = 0; i < data.length; i++) {
current[name] = data[i];
current = current[name];
}
console.log(JSON.stringify(json));
Which only returns the first item in the data array.
{
"name": [{
"desc": "A",
"age": 26
}]
}
Below code does what you want:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]
const value = data.reverse().reduce((acc, item) => {
return [{
...item[0],
name: acc
}]
});
console.log(value);
Though if you just had an array of objects instead of an array of arrays containing objects this would be slightly easier:
var data = [{desc:"A", age:26}, {desc:"B", age:12}, {desc:"C", age:48}]
data.reverse().reduce((acc, item) => {
return [{
...item,
name: acc
}]
});
You need to use recursion in this case since your are creating children.
In this code, we reduce the size of the array by removing the first element and passing it back to the same function
var data = [
[{desc:"A", age:26}],
[{desc:"B", age:12}],
[{desc:"C", age:48}]
]
function recursivelyAssignData(array) {
// we get the current element, to assign it a property "name",
const currentElement = array[0][0]
// we remove the first element, so it wont be pass to subsequent call of the function.
array.shift();
// if this is the last element, we don't want to assign the property "name" to it.
return array.length >= 1 ? Object.assign(currentElement, {
// we assign the value of same function, but with a different array.
name: recursivelyAssignData(array),
}) : currentElement;
}
const result = {request: recursivelyAssignData(data)};
console.log('results:', result , 'json:', JSON.stringify(result ));
P.S
Recursion might not be the most intuitive thing in the world, if you have trouble understand it, please ask question.
You are almost there. Since the values are inserted as first item in an array, use index 0 to access them.
const data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]];
const name = "name";
let result = {
[name]: data[0]
};
let obj = result;
for (let i = 1; i < data.length; i++) {
let current = obj[name][0];
current[name] = data[i];
obj = current;
}
console.log(result);

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

pushing strings into an object

I have an array of objects and an array of string and I am tying to combine the two in sequence meaning I would like to first item on the array to be stored only in the first object, second item of the array only in the second object, ect. Something like the following.
var objects = [ obj1, obj2, obj3];
var strings = ["123", "456", "789"];
//Result
var results = [
{
"obj1": {
number: "123"
},
{
"obj2": {
number: "456"
},
{
"obj2": {
number: "789"
}
];
I have been trying to do this with a push and a for loop but I seem to end up with each object containing all three strings.
Its easy:-
for (var i = 0; i < objects.length; i++) {// start loop for getting values one by one from object array
objects[i].number = strings[i]; // assign string values to object array values
}
Matched object and string share the same array index:
for (var i = 0; i < objects.length; i++) {
objects[i].number = strings[i];
}
Or you could do this using the map function:
var results = objects.map(function (value, index) {
return Object.assign({}, value, { number: strings[index] });
});
The other answers are good I just wanted to give you another way. This way you also do not modify the existing objects array
In case you don't know Object.assign add to the first argument (in our case the empty object {}) all the properties from the other object arguments. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Also, you can learn here about the map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

How to count the number of arrays nested within a JavaScript object by name

I have a generic function that needs to check the number of items in the array that is named, but I don't always know what the name is going to be called. Is there a way to do this?
array:
// added array example here per request:
var myArray = { "name": "myname", "data": [ "item1": [1], "item2": [2,3,4,5,6,7,8,9], "item3": [41,42,51,491]}
// where length is the number of objects in the array.
var mycount = someitem.getProperty("UnknownName").length;
what I want to do is call some function that does this:
var mycount = specialCountFunction(someitem, name);
In your specialCountFunction(), receive the property name as a string, and then use square brackets after item to evaluate the value of the string in order to use it as a property name.
function specialCountFunction(item, name) {
return item[name].length;
}
So then you'd call it like this:
var name = "whatever_the_name_is";
var count = specialCountFunction(someitem, name);
Do you mean to get the length of an array in an object?
For example, your object
var obj = {
"children": [ "john", "mark", "sam" ]
}
Get the length with obj["children"].length
Or the length of an object ?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(obj);

How to dynamically create a ARRAY based on a AJAX response?

How do I dynamically create a array after getting a AJAX response ?
The variable data.villages is my response.
I loop over its value using the jQuery each function:
$.each(data.villages, function(key, value) {
//Here I have the 2 variables: value.id and value.name
//Now I need to build a array where the value.id is the KEY and the content is name : value.name
//After I need to create an array with all the arrays
});
My final array should look like this:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
I need this to get the name value (or any other property) by knowing the ID....
Can you also show me example on how to get this data by knowing the ID ?
To create an array of objects from your json response you should be able to do something like this:
var arrayOfObjects = [];
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
arrayOfObjects.push(data.villages[i]);
}
What I think you actually want is an object. You can object like so:
var objectFromJson= {};
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
var currentItem = data.villages[i];
objectFromJson[currentItem.WhatEverPropertyYouWantForTheKey] = currentItem;
}
I think your final array is wrong:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
must be:
[
{ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] }
]
that is, an array with an object with the id=234141 and value [{name: ....}]
You can achieve that with:
data.villages = "your returned data array";
var newArray = [ { 234141: [] } ];
$.each(data.villages, function(key, value) {
newArray[0]['234141'].push({key: value};
}
you could try something like
arr = new Array();
arr[value.key] = {var1: 'vila1', var2: 'vila2'};
you are just storing json

Categories

Resources