Extract only values from JSON object in javascript without using a loop

前端 未结 4 974
暖寄归人
暖寄归人 2021-01-14 03:01

is there a \"Nice\" way to get all the values out of a json object (I don\'t care about the keys) - just get the values into array, without using a loop ? (lang is Javascr

4条回答
  •  遥遥无期
    2021-01-14 03:19

    It depends on how you define "loop".

    You can extract the properties with Object.keys and then map them to their values.

    … it's still essentially a loop under the hood though.

    var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
    var obj = JSON.parse(json);
    var values = Object.keys(obj).map(function (key) { return obj[key]; });
    console.log(values);

    With weaker browser support you could use the values method.

    var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
    var obj = JSON.parse(json);
    var values = Object.values(obj);
    console.log(values);

提交回复
热议问题