skip to Main Content

How to get single values from object.values array?

I am getting this obj in console.log() // {"item": Array(3)}

 {"item": (3) ['21', '14', '12']}

and I want to get single number from object.values // 21 ,14, 12

I am trying this

let j = Object.values(data)
  console.log(j)  // [Array(3)]

2

Answers


  1. Since I am not sure what data is present in the variable data. Let’s assume j is an array of elements.

    let j = {"items" : ['21', '14', '12']};
    

    If you want to print each element in the array individually, you can use forEach

    j.items.forEach(function(element) {
      console.log(element);
    });
    

    This will print

    21
    14
    12
    

    or if you need to print all the elements in a single line without a loop, You can use join

    let result = j.items.join(",");
    console.log(result);
    

    which will print

    21,14,12
    

    You can replace the , with whatever separator you wish to use.

    let j = {"items" : ['21', '14', '12']};
    
    console.log("List with loop");
    j.items.forEach(function(element) {
      console.log(element);
    });
    
    console.log("List with join");
    let result = j.items.join(",");
    console.log(result);
    Login or Signup to reply.
  2. Object.values() function returns all values (of various properties) in an object — itself in an array.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

    let data = {"item":['21', '14', '12']}
    let j = Object.values(data); //returns object values in an array
    j.map((item) => {
    if(!Array.isArray(item)){
      console.log(item)
    }
    else{
    item.map(val => console.log(val));
    }
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search