Problems extracting property names from an object (JAVASCRIPT) - javascript

I have an array of objects (I think!) and I need to extract the property name (for example "nickname") from a given object.
With
var VarObjAndValue = newArr[0];
I get the individual arrays (for example Object { nickname: “jhonny” }).
How can I now extract the property name "nickname" from the object above?
Listing the keys with
var listPropertyNames = Object.keys(newArr);
only provides sequential numbers from 0 to 6 rather than the desired keys names..
var StrToInclude = ["nickname", "name", "surname", "sex", "dob", "email", "phone"];
var newArr=[]; //Key name + its value
for (var i=0; i<StrToInclude.length; i++) {
temp_obj = {};
temp_obj[StrToInclude[i]] = document.getElementById(StrToInclude[i]).value;
newArr.push(temp_obj);
}
console.log('newArr --> = ',newArr);
/**
* newArr = [
* { "nickname": “jhonny” },
* { "name": “jonathan” },
* { "surname": “ross” },
* { "sex": “male” },
* { "dob": “22/02/1984” },
* { "email": “j#yahoo.com” },
* { "phone": "123" }
* ]
*/
var VarObjAndValue = newArr[0];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=0 ----> Object { nickname: “jhonny” }
var VarObjAndValue = newArr[1];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=1 ----> Object { name: "jonathan" }
var listPropertyNames = Object.keys(newArr);
console.log('listPropertyNames --> = ',listPropertyNames); //Array(7) [ "0", "1", "2", "3", "4", "5", "6" ] (not useful for this...)

newArr.map(obj => Object.keys(obj)).flat()
or newArr.map(obj => Object.keys(obj)[0])
or from dave's comment
newArr.reduce((keys, o) => [...keys, ...Object.keys(o)], [])
gives you all property names as an array
Not sure if this is what you want, but you have already gotten those property names in StrToInclude
const newArr =
[
{
"nickname": "jhonny"
},
{
"name": "jonathan"
},
{
"surname": "ross"
},
{
"sex": "male"
},
{
"dob": "22/02/1984"
},
{
"email": "j#yahoo.com"
},
{
"phone": "123"
}
]
console.log(newArr.map(obj => Object.keys(obj)[0]))

You are very close to getting the right answer. Since newArr is an Array, the keys are numeric keys. All you have to do is go through each element is the Array of Objects to extract the keys. Something like this should do nicely:
for(let i = 0;i<newArr.length;i++){
console.log(Object.keys(newArr[i])); //Will go through the whole array and give you the keys of every object in it
}

You can simply do by looping over the array and using destructuring operator with the desired property name.
const arr = [
{
nickname: "abdullah"
},
{
age: 27
}
];
arr.forEach(({nickname}) => {
if (nickname) {
console.log(`Thats the property we want to extract: ${nickname}`);
break; // if you are not expecting this property name in other objects, otherwise no need to break
}
});

Related

Dynamically creating an object with an array inside

I'm trying to dynamically create a JS object which has an array inside such as this one:
//other values omitted for clarity
"items": [
{
"name": "T-Shirt",
"unit_amount": {
"currency_code": "USD",
"value": "90.00"
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
},
{
"name": "Shoes",
"unit_amount": {
"currency_code": "USD",
"value": "45.00"
},
"quantity": "2",
"category": "PHYSICAL_GOODS"
}
],
I am able to create a single value with this code:
var product = {};
product.name = "T-Shirt";
product.quantity = "1";
product.category = "PHYSICAL_GOODS";
var subproduct = {};
subproduct.currency_code = "USD";
subproduct.value = "90.00";
product.unit_amount = subproduct;
var jsonString= JSON.stringify(product);
Which creates:
{
"name": "T-Shirt",
"unit_amount": {
"currency_code": "USD",
"value": "90.00"
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
}
How can I add up the created values inside the array? I have an onclick event for providing the values for any given "item" in the example. For clarity, I do not know beforehand how many "items" the array will have.
To add the object to an array you should use the array method .push().
You could do it in the following way:
// Object which has a property `items`, where we will store product objects
var main = {
items: []
};
// Create the full product object
var product = {
name: "T-Shirt";
quantity: "1";
category: "PHYSICAL_GOODS";
unit_amount: {
currency_code = "USD";
value = "90.00";
}
};
// Push the new object to the `items` array
main.items.push(product);
You are on the right path, just iterate your code and put it in an array :
var productList = [];
for (var i = 0 ; i < 2; i++) {
// your code
var product = {};
product.name = "T-Shirt";
product.quantity = "1";
product.category = "PHYSICAL_GOODS";
var subproduct = {};
subproduct.currency_code = "USD";
subproduct.value = "90.00";
product.unit_amount = subproduct;
productList.push(product);
}
var answer = JSON.stringify(productList);
console.log(answer);

Create a new object in Angular 11 app based on values in another array of objects

I am having an Angular 11 app in which I have an array of objects as shown below.
details = [
{
"name": "firstName",
"content": "Tom"
},
{
"name": "lastName",
"content": "Smith"
},
{
"name": "email",
"content": "tomsmith#test.com"
}
]
I want to create an object from above array as shown below.
output = {
firstName: {value: "Tom"},
lastName: {value: "Smith"},
email: {value: "tomsmith#test.com"}
}
For simplicity I have only shown 3 objects in the details array but there can be any number of them. So I want the conversion to happen irrespective of the number of objects in the details array. How can I create the above output object? Please help me out.
you could do with Array#reduce.
const details = [ { "name": "firstName", "content": "Tom" }, { "name": "lastName", "content": "Smith" }, { "name": "email", "content": "tomsmith#test.com" } ];
const res = details.reduce(
(acc, {name, content: value}) => (acc[name] = {value}, acc), {}
);
console.log(res)
Not that I'm against to the other answers proposed. As an alternative you can also do it with the help of a "for-of" loop and applying destructured assignment.
const details = [ { "name": "firstName", "content": "Tom" }, { "name": "lastName", "content": "Smith" }, { "name": "email", "content": "tomsmith#test.com" } ];
let result = {}
for ({ name: n, content: value } of details) { result[n] = { value: value }; }
console.log(result)
MDN Reference - Deconstructuring Assignment
Map the array to an array of [name, { value }] pairs, and convert to an object using Object.fromEntries().
With Typescript you'll need to set the target as ES2019 at least in your TS config, and it doesn't require any type definition (TS Playground).
const details = [{"name":"firstName","content":"Tom"},{"name":"lastName","content":"Smith"},{"name":"email","content":"tomsmith#test.com"}]
const result = Object.fromEntries(
details.map(({ name, content: value }) => [name, { value }])
)
console.log(result)

How to push values to an object from inside a map function when a condition is met?

How can we push values to an object from inside a map function and return that single object. I have string comparison condition inside the map function. I tried using Object.assign but it returns an array with multiple object inside that array. Instead of this multiple object I'm expecting a single object inside an array.
Map function
let arrayObj = arrayToTraverse.map(function(item) {
var myObj = {};
if(item.inputvalue === 'Name'){
Object.assign(myObj, {name: item.value});
} else if (item.inputvalue === 'Email'){
Object.assign(organizerInfo, {email: item.value});
} else if (item.inputvalue === 'Company'){
Object.assign(organizerInfo, {company: item.value});
}
return myObj;
});
console.log("The array object is", arrayObj)
This return the array of objects as follows
[
{
"name": "Tom"
},
{
"email": "tom#abc.com"
},
{
"company": "ABC"
}
]
But The array I'm expecting is
[
{
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
// or
[
"returned": {
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
An example of arrayToTraverse can be considered as following
[
{
"id": "1",
"inputvalue": "Name",
"value": "Tom",
"type": "Short Text"
},
{
"id": "2",
"inputvalue": "Email",
"value": "tom#abc.com",
"type": "Email ID"
},
{
"id": "3",
"inputvalue": "Company",
"value": "Google",
"type": "Long Text"
}
]
Simply put, you're trying to reduce an array to a single object, not map one array to another.
var arrayToTraverse = [
{inputvalue:"Name",value:"Tom"},
{inputvalue:"Email",value:"tom#abc.com"},
{inputvalue:"Company",value:"ABC"},
{inputvalue:"Foo",value:"Bar"} // wont show up
];
var valuesRequired = ["Name","Email","Company"];
var result = arrayToTraverse.reduce( (acc, item) => {
if(valuesRequired.includes(item.inputvalue))
acc[item.inputvalue.toLowerCase()] = item.value;
return acc;
}, {});
console.log(result);
Edit: Added lookup array for required fields.

How to append object-key value form one array to other array?

I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:
Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"
If a object is removed or added in the New array, it have to do the same to the Current array.
As far I can see now, I can use some es6 functions :) like:
object-assign, but how to set the new key "fan_count_new"?
How to loop through the array to compare and add or remove + copy the fan_count?
Current array:
[{
"fan_count": 1234,
"id": "1234567890",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
},
{
"fan_count": 4321,
"id": "09876543210",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
}, ...
]
New array:
[{
"fan_count": 1239,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
"id": "1234567890"
},
{
"fan_count": 4329,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
},
"id": "09876543210"
}, ...
]]
You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:
var currArr = [
{
"fan_count": 1234,
"id": "1234567890",
},
{
"fan_count": 4321,
"id": "09876543210",
},
{
"fan_count": 4321,
"id": "09876543215",
}
];
var newArr = [
{
"fan_count": 1234,
"id": "1234567890"
},
{
"fan_count": 5555,
"id": "09876543210"
}
];
currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
found.fan_count_new = obj.fan_count;
}
});
console.log(currArr);
Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
console.log('found: ', found.fan_count, obj.fan_count)
obj.fan_count_prev = found.fan_count;
obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
}
if (typeof obj.fan_count_prev === "undefined") {
obj.fan_count_prev = obj.fan_count;
obj.fan_count_diff = 0
}
});

javascript and json

I'm using javascript with a json library and running into a little trouble. Here's my json output:
{
"artist": {
"username": "myname",
"password": "password",
"portfolioName": "My Portfolio",
"birthday": "2010-07-12 17:24:36.104 EDT",
"firstName": "John",
"lastName": "Smith",
"receiveJunkMail": true,
"portfolios": [{
"entry": [{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}]
}]
}
}
In javascript I'm trying to access the entries in the map like so:
var portfolios = jsonObject.artist.portfolios.entry;
var portfolioCount = portfolios.length;
for ( var index = 0; index < portfolioCount; index++ )
{
var portfolio = portfolios[index];
txt=document.createTextNode("Portfolio Name: " + portfolio['string'] );
div = document.createElement("p");
div.appendChild ( txt );
console.appendChild(div);
}
but portfolios is "undefined". What's the correct way to do this?
Look at your JSON results. portfolios is a one-element array; portfolios[0] is an object containing a single key, entry, which maps to an array of two objects that have both string and utils.Portfolio keys. Thus, the syntax jsonObject.artist.portfolios.entry will not work. Instead, you want jsonObject.artist.portfolios[0].entry.
If possible, I would suggest changing whatever code generates those JSON results to remove the entry level of indirection entirely, e.g. like so:
{
"artist": {
/* ... */
"portfolios": [
{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}
]
}
}
Then you could access it with
var portfolios = jsonObject.artist.portfolios;
for (var i = 0, portfolio; portfolio = portfolios[i]; ++i)
{
// use portfolio variable here.
}
There is an array in your object. I believe you're looking for this:
var portfolios = jsonObject.artist.portfolios[0].entry;
The portfolios property is an array, so you need to use an index to get the first element:
var portfolios = jsonObject.artist.portfolios[0].entry;

Categories

Resources