更改vue3中的对象typeScript

niknxzdl  于 2023-02-25  发布在  TypeScript
关注(0)|答案(3)|浏览(235)

我的原始对象如下(对象名是runOverview)。我想删除粗体字段版本、输入、加载、产品和project_name。
{"版本":"1","输入":[{"名称":"输入1","值":"1,827 "},{"姓名":"输入2","值":"310 "}],"加载":[{"名称":"负载1","值":"440 "},{"姓名":"负载2","值":"220 "},{"姓名":"负载3","值":"46 "}]、"产品":[{"名称":"产品1","价值":"15,000 "},{"姓名":"产品3"、"价值":"4.8 "}]、"项目名称":"测试"}
我想更改runOverview对象,如下所示(预期输出)。

{{
      "name": "input1",
      "value": "1,827"
    },
    {
      "name": "input2",
      "value": "310"
    },
    {
      "name": "loads1",
      "value": "440"
    },
    {
      "name": "loads2",
      "value": "220"
    },
    {
      "name": "loads3",
      "value": "46"
    },
    {
      "name": "products1",
      "value": "15,000"
    },
    {
      "name": "products3",
      "value": "4.8"
    }}

我已经尝试了以下方法

const overviewDetails = computed(() => {
  const overviewArr = [];
    for ( var newdata in runOverview.value) {
      overviewArr.push(newdata)
    }
  return overviewArr
});
    • 请帮助我创建仅具有必需属性的新对象数组**
7cjasjjr

7cjasjjr1#

这是非常强大的它将合并任何属性的值是一个数组.我相信这是你想要的:

// </script><script type="module">
import { ref, computed } from "https://unpkg.com/vue@3.2.47/dist/vue.runtime.esm-browser.js"

const runOverview = ref({ "version": "1", "inputs": [ { "name": "input1", "value": "1,827" }, { "name": "input2", "value": "310" } ], "loads": [ { "name": "loads1", "value": "440" }, { "name": "loads2", "value": "220" }, { "name": "loads3", "value": "46" } ], "products": [ { "name": "products1", "value": "15,000" }, { "name": "products3", "value": "4.8" } ], "project_name": "Test" })

const overviewDetails = computed(() => {
  return Object.values(runOverview.value).reduce((r, item) => {
    if (Array.isArray(item)) r.push(...item)

    return r
  }, [])
})

console.log(overviewDetails.value)
zlwx9yxi

zlwx9yxi2#

可以使用reducemap方法。请尝试以下操作:

<script type="module">
import { ref, computed } from "https://unpkg.com/vue@3.2.47/dist/vue.runtime.esm-browser.js"

const runOverview = ref({version:"1",inputs:[{name:"input1",value:"1,827"},{name:"input2",value:"310"},],loads:[{name:"loads1",value:"440"},{name:"loads2",value:"220"},{name:"loads3",value:"46"},],products:[{name:"products1",value:"15,000"},{name:"products3",value:"4.8"},],project_name:"Test"});

 const overviewDetails = computed(() =>
  ["inputs", "loads", "products"].reduce(
    (acc, key) =>
      acc.concat(
        runOverview.value[key].map((item) => ({
          name: item.name,
          value: item.value,
        }))
      ),
    []
  )
);
console.log(overviewDetails.value)

</script>
uttx8gqw

uttx8gqw3#

const arr = []
Object.values(runOverview).forEach(item => {
        if(Array.isArray(item)) {
            arr.push(...item)
        }
    })
console.log(arr)

相关问题